编写一个定制的收集器

 

 

 //编写一个定制的收集器
 List<String> names = Arrays.asList("shekhar", "rahul", "shekhar");
 Multiset<String> set = names.stream().collect(new MultisetCollector<>());
 set.forEach(str -> System.out.println(str + ":" + set.count(str)));



 //编写一个定制的收集器
    public static class MultisetCollector<T> implements Collector<T, Multiset<T>, Multiset<T>> {

        @Override
        public Supplier<Multiset<T>> supplier() {
            return HashMultiset::create;
        }

        @Override
        public BiConsumer<Multiset<T>, T> accumulator() {
            return (set, e) -> set.add(e, 1);
        }

        @Override
        public BinaryOperator<Multiset<T>> combiner() {
            return (set1, set2) -> {
                set1.addAll(set2);
                return set1;
            };
        }

        @Override
        public Function<Multiset<T>, Multiset<T>> finisher() {
            return Function.identity();
        }

        @Override
        public Set<Characteristics> characteristics() {
            return Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH));
        }
    }

 

上一篇:Java中的虚假唤醒真的发生了吗?


下一篇:Redis学习-05 Set集合基本操作