2024-03-28 Java8之Collectors类

发布于:2024-04-01 ⋅ 阅读:(138) ⋅ 点赞:(0)

Collectors类常用方法

1.toList、toSet、toMap

Collector<T, ?, List<T>> toList(); //收集为List集合
Collector<T, ?, Set<T>> toSet(); //Set
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper)//Map
//收集code为新List集合
List<String> strList = list.stream().map(DemoObj::getCode).collect(Collectors.toList());
//收集code为新Set集合
Set<String> collect = list.stream().map(DemoObj::getCode).collect(Collectors.toSet());
//将code为key,amount为值作为map集合
Map<String, Integer> collect = list.stream().collect(Collectors.toMap(DemoObj::getCode, DemoObj::getAmount));

2.joining、counting、summingInt、minBy

//指定字符拼接
Collector<CharSequence, ?, String> joining(CharSequence delimiter); 
//统计 等同于Stream的count()
<T> Collector<T, ?, Long> counting();
//求和,等同于Stream的mapToInt(ToIntFunction<? super T> mapper).sum()
<T> Collector<T, ?, Integer> summingInt(ToIntFunction<? super T> mapper) 
//获取最小值,等同于Stream的min(Comparator<? super T> comparator)
<T> Collector<T, ?, Optional<T>>  minBy(Comparator<? super T> comparator) 
//遍历list集合取将DemoObj对象的code属性用逗号拼接
String str = list.stream().map(DemoObj::getCode).collect(Collectors.joining(","));
Long collect = list.stream().map(DemoObj::getCode).collect(Collectors.counting());
//求和,等同于mapToInt(DemoObj::getAmount).sum()
Integer collect = list.stream().collect(Collectors.summingInt(DemoObj::getAmount));
//获取最小金额,等同于 min(Comparator.comparingInt(DemoObj::getAmount))
Optional<DemoObj> collect = list.stream().collect(Collectors.minBy(Comparator.comparingInt(DemoObj::getAmount)));

3.groupingBy

<T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier);//分组
Map<Integer, List<DemoObj>> collect = list.stream().collect(Collectors.groupingBy(DemoObj::getAmount));//按金额分组

网站公告

今日签到

点亮在社区的每一天
去签到