Collectors工具类

Collector是专门用来作为Stream的collect方法的参数的;而Collectors是作为生产具体Collector的工具类。

Collectors是一个工具类,是JDK预实现Collector的工具类,它内部提供了多种Collector,我们可以直接拿来使用,非常方便。

具体用法

public class Collectors_example {

    public static void main(String[] args) {
        List<Apple> appleList = new ArrayList<>();
        appleList.add(new Apple("red", 170));
        appleList.add(new Apple("green", 150));
        appleList.add(null);
        appleList.add(new Apple("yellow", 170));
        appleList.add(new Apple("green", 100));
        appleList.add(new Apple("red", 170));


        //joining: 拼接
        String join = appleList.stream().map(x -> x.getColor()).collect(Collectors.joining());
        String join1 = appleList.stream().map(x -> x.getColor()).collect(Collectors.joining("-"));
        String join2 = appleList.stream().map(x -> x.getColor()).collect(Collectors.joining("-", "前缀", "后缀"));
        System.out.println(join2);

        //toCollection、toList与toSet
        ArrayList<Integer> arrayList = appleList.stream().map(x -> x.getWeight()).collect(Collectors.toCollection(ArrayList::new));
        List<Integer> arrayList1 = appleList.stream().map(x -> x.getWeight()).collect(Collectors.toList());
        Set<Integer> hashSet = appleList.stream().map(x -> x.getWeight()).collect(Collectors.toSet());

        System.out.println("----------------------------------");
        //toMap与toConcurrentMap: 键不能重复!!! toConcurrentMap同toMap
        Map<String, Integer> map4 = appleList.stream().collect(Collectors.toMap(Apple::getColor, Apple::getWeight));
        Map<Integer, Integer> map5 = appleList.stream().collect(Collectors.toMap(Apple::getWeight, x -> 1, Integer::sum));
        Hashtable<Integer, Integer> hashtable = appleList.stream().collect(Collectors.toMap(Apple::getWeight, x -> 1, Integer::sum, Hashtable::new));
        System.out.println(map5);
        System.out.println(hashtable);

        //reducing: 对输入元素执行汇聚操作
        Apple apple = appleList.stream().collect(Collectors.reducing(BinaryOperator.maxBy(Comparator.comparingInt(Apple::getWeight)))).orElse(null);
        Integer inte = appleList.stream().map(x -> x.getWeight()).collect(Collectors.reducing(10000, Integer::sum));
        Integer inte1 = appleList.stream().collect(Collectors.reducing(0, Apple::getWeight, Integer::sum));
        System.out.println(inte1);

        /******************求值: list中如果存在空元素会抛空指针异常!!******************/
        //averaging: 平均值 
        //averagingInt/averagingLong/averagingDouble
        Double collect = appleList.stream().collect(Collectors.averagingDouble(Apple::getWeight));
        System.out.println(collect);

        //counting: 统计个数
        Long count = appleList.stream().collect(Collectors.counting());
        Long emptyCount = Stream.empty().collect(Collectors.counting());
        //Stream.count()方法的返回值是long型,counting()方法返回值是Collector类型
        long streamCount = appleList.stream().count();
        System.out.println(count);
        System.out.println(emptyCount);

        //maxBy、minBy: 最大最小值
        appleList.stream().collect(Collectors.maxBy(Comparator.comparingInt(Apple::getWeight))).ifPresent(System.out::println);
        appleList.stream().collect(Collectors.minBy(Comparator.comparingInt(Apple::getWeight))).ifPresent(System.out::println);

        //summing、summarizing: 求和
        Integer sum1 = appleList.stream().collect(Collectors.summingInt(Apple::getWeight));
        IntSummaryStatistics iss = appleList.stream().collect(Collectors.summarizingInt(Apple::getWeight));
        System.out.println(iss.getMax());
        System.out.println(iss.getMin());
        System.out.println(iss.getCount());
        System.out.println(iss.getSum());
        System.out.println(iss.getAverage());


        /******************分组******************/
        //groupingBy: 分组
        Map<String, List<Apple>> map = appleList.stream().collect(Collectors.groupingBy(Apple::getColor));
        Map<String, Long> longMap = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.counting()));
        TreeMap<String, Long> treeMap = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, TreeMap::new, Collectors.counting()));
        longMap.forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });

        //groupingByConcurrent: 操作同groupingBy; 元素整理成ConcurrentMap(线程安全)
        ConcurrentMap<String, List<Apple>> map1 = appleList.stream().collect(Collectors.groupingByConcurrent(Apple::getColor));

        //partitioningBy: 分区;例:大于150的一个组,小于150的一个组
        Map<Boolean, List<Apple>> map2 = appleList.stream().collect(Collectors.partitioningBy(x -> x.getWeight() > 150));
        Map<Boolean, Long> map3 = appleList.stream().collect(Collectors.partitioningBy(x -> x.getWeight() > 150, Collectors.counting()));
        map3.forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });

        //collectingAndThen: 收集后操作
        String avg = appleList.stream().collect(Collectors.collectingAndThen(Collectors.averagingInt(Apple::getWeight), item -> "average weight is " + item));
        System.out.println(avg);

        //mapping: 在调用mapper之后,将调用结果的返回值作为downstream的输入元素,再调用downstream
        String collect1 = appleList.stream().collect(Collectors.mapping(Apple::getColor, Collectors.joining("-")));
        System.out.println(collect1);


    }

    /******************自定义******************/
    public static <T> Collector<T, Set<T>, Set<T>> toImmutableSet() {
        return Collector.of(HashSet::new, Set::add, (left, right) -> {
            left.addAll(right);
            return left;
        }, t -> t, Collector.Characteristics.IDENTITY_FINISH);
    }

    public static <T, A extends Set<T>> Collector<T, A, Set<T>> toImmutableSet(Supplier<A> supplier) {
        return Collector.of(
                supplier,
                Set::add, (left, right) -> {
                    left.addAll(right);
                    return left;
                }, Collections::unmodifiableSet);
    }

}

 

posted @ 2020-10-13 10:37  柒月丶  阅读(476)  评论(0)    收藏  举报