java8->Collectors.mapping+Collectors.reducing+TreeSet等等

 @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);

        // 最小值 1
        Integer 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);


    }