芯が強い人になるESTJ-A

# JAVA stream.collect整理

IT開発 Tags: 无标签 阅读: 219

分组

Map<Integer,List<Entity>> groupBy = entityList.stream().collect(Collectors.groupingBy(Entity::getGrouper));

转Map

Map<Integer,Entity> entityMap = entityList.stream().collect(Collectors.toMap(Entity::getKey,entity->entity));

###分组

Map<Integer,List<Entity>> groupBy = entityList.stream().collect(Collectors.groupingBy(Entity::getGrouper));


###转Map
Map<Integer,Entity> entityMap = entityList.stream().collect(Collectors.toMap(Entity::getKey,entity->entity));

案例:toList/toSet/(toCollection)

words = Stream.of("GNU","not","Unix","GNU");
System.out.println(words.collect(Collectors.toSet()));
输出://[Unix, not, GNU]

案例:summingLong、summingInt、summingDouble

//        统计字母数
    Stream<String> words = Stream.of("GNU","not","Unix","GNU");
        int count = words.collect(Collectors.summingInt(String::length));
        System.out.println(count);//13

案例:summarizingInt/summarizingLong/summarizingDouble

//        统计字母数出现次数数据
        Stream<String> words = Stream.of("GNU","not","Unix","GNU");
        IntSummaryStatistics summaryStatistics = words.collect(Collectors.summarizingInt(String::length));
        System.out.println(summaryStatistics);//IntSummaryStatistics{count=4, sum=13, min=3, average=3.250000, max=4}

案例:toMap/toConcurrentMap及各种重载形式
①入参说明
keyMapper:将stream内部元素映射为key的表达式
valueMapper:将stream内部元素映射为value的表达式
mergeFunction:当同一个key对应的value冲突时,重新映射的表达式
mapSupplier:map的supplier

②出参说明
见方法实现,其中mapMerger中解决冲突时同样调用mergeFunction解决

③重构形式
不传入mapSupplier,mapSupplier默认为HashMap::new
不传入mapSupplier和mergeFunction,mapSupplier默认为HashMap::new,在发生value冲突时会报错


public static <T, K, U, M extends Map<K, U>>
    Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
                                Function<? super T, ? extends U> valueMapper,
                                BinaryOperator<U> mergeFunction,
                                Supplier<M> mapSupplier) {
        BiConsumer<M, T> accumulator
                = (map, element) -> map.merge(keyMapper.apply(element),
                                              valueMapper.apply(element), mergeFunction);
        return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
    }

groupingBy/groupingByConcurrent及其重载形式

//        返回各单词出线的频次,频次统计中忽略大小写,所以单词一律全大写再统计
        Stream<String> words = Stream.of("GNU","not","Unix","Matter","Gnu","NOT");
        Map<String,Long> stat = words.collect(Collectors.groupingBy(String::toUpperCase,Collectors.counting()));
//        上述等同于
//        Map<String,Long> stat = words.collect(Collectors.groupingBy(
//                String::toUpperCase,
//                Collectors.reducing(0L,(word)->1L,(x, y)->x+y)
//                ));
        System.out.println(stat);
//  输出: {MATTER=1, NOT=2, UNIX=1, GNU=2}