StreamAPI練習

練習一

新建交易員類

//新建交易員類
public class Trader {

    private String name;
    private String city;

    public Trader() {
    }

    public Trader(String name, String city) {
        this.name = name;
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Trader{" +
            "name='" + name + '\'' +
            ", city='" + city + '\'' +
            '}';
    }
}

新建交易類

//交易類,聚合了交易員類
public class Transaction {
	private Trader trader;
	private int year;
	private int value;

	public Transaction() {
	}
	public Transaction(Trader trader, int year, int value) {

		this.trader = trader;
		this.year = year;
		this.value = value;
	}

	public Trader getTrader() {
		return trader;
	}

	public void setTrader(Trader trader) {
		this.trader = trader;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}

	@Override
	public String toString() {
		return "Transaction{" +
				"trader=" + trader +
				", year=" + year +
				", value=" + value +
				'}';
	}
}

測試類

public class TraderTest {

    Trader raoul = new Trader("Raoul", "Cambridge");
    Trader mario = new Trader("Mario", "Milan");
    Trader alan = new Trader("Alan", "Cambridge");
    Trader brian = new Trader("Brian", "Cambridge");

    List<Transaction> transactions = Arrays.asList(
        new Transaction(brian, 2011, 300),
        new Transaction(raoul, 2012, 1000),
        new Transaction(raoul, 2011, 400),
        new Transaction(mario, 2012, 710),
        new Transaction(mario, 2012, 700),
        new Transaction(alan, 2012, 950)
    );

    /*

		1、找出2011年發生的所有交易,並按照交易額排序(從低到高)
		2、交易員都在那些不同的城市工作過
		3、查找所有來自劍橋的交易員,並按照名字排序
		4、返回所有交易員的姓名字符串,按照字母順序排序
		5、有沒有交易員是在米蘭工作的
		6、打印生活在劍橋的交易員的所有交易額
		7、所有交易中,最高的交易額是多少
		8、找到交易額最小的交易
	 */

    /**
	 * 1、找出2011年發生的所有交易,並按照交易額排序(從低到高)
	 */
    @Test
    public void test1() {
        transactions.stream()
            .filter((x) -> x.getYear()==2011)
            .sorted((x,y) -> Double.compare(x.getValue(),y.getValue()))
            .forEach(System.out::println);
//Transaction{trader=Trader{name='Brian', city='Cambridge'}, year=2011, value=300}
//Transaction{trader=Trader{name='Raoul', city='Cambridge'}, year=2011, value=400}
    }

    /**
	 * 2、交易員都在那些不同的城市工作過
	 */
    @Test
    public void test2() {
        transactions.stream()
            .map((x) -> x.getTrader().getCity())
            .distinct()
            .forEach(System.out::println);
        //Cambridge
        //Milan

    }

    /**
	 * 3、查找所有來自劍橋的交易員,並按照名字排序
	 */
    @Test
    public void test3() {
        transactions.stream()
            .filter((x) -> x.getTrader().getCity().equals("Cambridge"))
            .map((x) -> x.getTrader().getName())
            .sorted()
            .forEach(System.out::println);
        //Alan
        //Brian
        //Raoul
        //Raoul
    }

    /**
	 * 4、返回所有交易員的姓名字符串,按照字母順序排序
	 */
    @Test
    public void test4() {

        String str = transactions.stream()
            .map((x) -> x.getTrader().getName())
            .sorted()
            .reduce((x, y) -> x +","+ y)
            .get();
        System.out.println("str = " + str);
        //str = Alan,Brian,Mario,Mario,Raoul,Raoul

        String str2 = transactions.stream()
            .map((x) -> x.getTrader().getName())
            .sorted()
            .collect(Collectors.joining(","));
        System.out.println("str2 = "+str2);
        //str = Alan,Brian,Mario,Mario,Raoul,Raoul

    }

    /**
	 * 5、有沒有交易員是在米蘭工作的
	 */
    @Test
    public void test5() {
        boolean milan = transactions.stream()
            .anyMatch((x) -> x.getTrader().getCity().equals("Milan"));
        System.out.println("milan = " + milan);
        //milan = true

    }

    /**
	 * 6、打印生活在劍橋的交易員的所有交易額
	 */
    @Test
    public void test6() {

        Optional<Integer> sum = transactions.stream()
            .filter((x) -> x.getTrader().getCity().equals("Cambridge"))
            .map((x) -> x.getValue())
            .reduce(Integer::sum);
        System.out.println("sum = " + sum.get());
        //sum = 2650
    }

    /**
	 * 7、所有交易中,最高的交易額是多少
	 */
    @Test
    public void test7() {
        Optional<Integer> max = transactions.stream()
            .map(Transaction::getValue)
            .max((x,y) -> x-y);
        System.out.println(max.get()); //1000

    }

    /**
	 * 8、找到交易額最小的交易
	 */
    @Test
    public void test8() {
        Optional<Integer> min = transactions.stream()
            .map(Transaction::getValue)
            .min((x,y) -> x-y);
        System.out.println("min = "+min.get()); //min = 300

        DoubleSummaryStatistics collect = transactions.stream()
            .collect(Collectors.summarizingDouble((x) -> x.getValue()));
        double min1 = collect.getMin();
        System.out.println("min1 = " + min1);//min1 = 300.0

    }


}

練習二

/**
	 * function:給定一個數字列表,如果返回一個由每個數的平方構成的列表
	 * 給定[1,2,3,4,5],返回[,1,4,9,16,25]
	 */
@Test
public void test22(){
    int[] arr = {1,2,3,4,5};
    int[] arr2 = Arrays.stream(arr)
        .map((x) -> x * x)
        .toArray();
    System.out.println("arr2 = " + Arrays.toString(arr2));
    //arr2 = [1, 4, 9, 16, 25]

}

練習三

/**
	 *
	 * function:怎麼用map和reduce方法數一數流中有多少個Employee呢
	 *
	 */
@Test
public void test23(){
    Optional<Integer> reduce = employees.stream()
        .map((x) -> 1)
        .reduce((x, y) -> x + y);
    System.out.println("reduce = " + reduce.get());  //reduce = 6

    Optional<Integer> reduce1 = employees.stream()
        .map((x) -> 1)
        .reduce(Integer::sum);
    System.out.println("reduce1 = " + reduce1.get()); //reduce1 = 6

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章