java8->Collectors.mapping+Collectors.reducing+TreeSet等等
阿新 • • 發佈:2020-09-09
@Test public void demo9(){ // 求最大值 3 List<Integer> list = Arrays.asList(1, 2, 3); Integer maxValue = list.stream().collect(Collectors.collectingAndThen(Collectors.maxBy((a, b) -> a - b), Optional::get)); System.out.println("最大值:"+maxValue); // 最小值 1Integer minValue = list.stream().collect(Collectors.collectingAndThen(Collectors.minBy((a, b) -> a - b), Optional::get)); System.out.println("最小值:"+minValue); // 求和 6 Integer sumValue = list.stream().collect(Collectors.summingInt(item -> item)); System.out.println("求和:"+sumValue); // 平均值 2.0 Double avg = list.stream().collect(Collectors.averagingDouble(x -> x)); System.out.println("平均值:"+avg); // 對映:先對集合中的元素進行對映,然後再對對映的結果使用Collectors操作 // A,B,C System.out.println("大寫:"+Stream.of("a", "b", "c").collect(Collectors.mapping(x -> x.toUpperCase(), Collectors.joining(","))));// sum: 是每次累計計算的結果,b是Function的結果 System.out.println("return:"+Stream.of(1, 3, 4).collect(Collectors.reducing(0, x -> x + 1, (sum, b) -> { System.out.println("sum:"+sum + "->b:" + b); return sum + b; }))); // 注意reducing可以用於更復雜的累計計算,加減乘除或者更復雜的操作 // result = 2 * 4 * 5 = 40 System.out.println("return:"+Stream.of(1, 3, 4).collect(Collectors.reducing(1, x -> x + 1, (result, b) -> { System.out.println("result:"+result + "->b:" + b); return result * b; }))); // Collectors.joining(",")的結果是:a,b,c 然後再將結果 x + "d"操作, 最終返回a,b,cd String str= Stream.of("a", "b", "c").collect(Collectors.collectingAndThen(Collectors.joining(","), x -> x + "d")); System.out.println("str: "+str); List<Integer> list1 = Arrays.asList(1, 2, 3); // [10, 20, 30] List<Integer> collect = list1.stream().map(i -> i * 10).collect(Collectors.toList()); // [20, 10, 30] Set<Integer> collect1 = list1.stream().map(i -> i * 10).collect(Collectors.toSet()); // {key1=value:10, key2=value:20, key3=value:30} Map<String, String> collect2 = list1.stream().map(i -> i * 10).collect(Collectors.toMap(key -> "key" + key/10, value -> "value:" + value)); // [1, 3, 4] TreeSet<Integer> collect3= Stream.of(1, 3, 4).collect(Collectors.toCollection(TreeSet::new)); System.out.println(collect+"\n"+collect1+"\n"+collect2+"\n"+collect3); }