本文主要是介绍2024-03-28 Java8之Collectors类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Collectors类常用方法
文章目录
- Collectors类常用方法
- 1.toList、toSet、toMap
- 2.joining、counting、summingInt、minBy
- 3.groupingBy
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));//按金额分组
这篇关于2024-03-28 Java8之Collectors类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!