背景
在Java 8中,Stream API的引入极大地提升了对集合数据处理的灵活性和效率,而Collectors类更是为数据的收集和聚合提供了强大的工具。本文将深入探讨如何利用List集合.stream().collect()这一链式调用,实现集合数据的高效转换与聚合,为你的编程之旅增添一抹亮色。
引言
Java 8以前,我们处理集合数据时,往往需要通过循环遍历、手动创建新的集合来实现转换和聚合操作,这种方式不仅代码冗长,而且难以阅读和维护。随着Stream API的出现,一切变得简洁而高效。stream()方法将集合转换为Stream流,而collect()方法则用于将流中的数据按照指定规则收集到一个新的容器中,或者聚合为一个值,如计数、求和等。
基础概念
•Stream:一个支持链式操作的元素序列,可以对集合数据进行操作,如过滤、排序、映射等,而无需显式迭代。
•Collectors:一个工具类,提供了多个静态方法,帮助我们将流转换为另一种数据结构,或者执行聚合操作。
使用场景
1.数据转换
假设我们有一个List<String>,里面存储了一组用户名称,现在我们需要将所有用户名转换为大写并收集到一个新的列表中。List<String> names = Arrays.asList("张三", "李四", "王五","小李子");
List<String> uppercaseNames = names.stream().map(String::toUpperCase).collect(Collectors.toList());
2.数据聚合
如果我们需要统计这些用户名中长度大于5的名字有多少个,可以这样做:
long count = names.stream().filter(name -> name.length() > 5).collect(Collectors.counting());
3.分组
对于复杂的数据处理,比如需要按用户名首字母分组,可以使用groupingBy:
Map<Character, List<String>> groupedNames = names.stream().collect(Collectors.groupingBy(name -> name.charAt(0)));
4.归约
如果需要将所有用户名合并为一个字符串,每两个用户名之间用逗号分隔,可以使用joining:String concatenatedNames = names.stream().collect(Collectors.joining(", "));
进阶技巧
1.多级收集
可以结合使用多个收集器,例如,先分组后统计每组的数量。
Map<Character, Long> groupAndCount = names.stream().collect(Collectors.groupingBy(name -> name.charAt(0),Collectors.counting()));
2.分区
使用partitioningBy可以根据条件将数据分为两部分。
Map<Boolean, List<String>> partitionedNames = names.stream().collect(Collectors.partitioningBy(name -> name.length() > 5));
3.键值对
使用Collectors.toMap可以得到键值对的数据结构
Map<String, MerchantOrderInfo> map = list.stream().collect(Collectors.toMap(MerchantOrderInfo::getOrderNumber, Function.identity(),(existing, relacement)->existing));
4.高级键值对,值为集合
Map<String, List<MerchantOrderInfo>> map= list.stream().collect(Collectors.groupingBy(MerchantOrderInfo::getOrderNumber, Collectors.toList()));
结尾:
个人经验总结,不喜勿喷,大家多多交流!