Java Stream Collectors 用法

Java Stream 的 Collectors 类提供了大量用于将流中元素收集到不同数据结构或执行聚合操作的工具方法。以下是其主要用法和高级功能:

1. 基础收集方法

toList()toSet()toMap()

这些是最常用的收集方法,分别将流元素收集到 ListSetMap 中:

List<String> list = stream.collect(Collectors.toList()); Set<String> set = stream.collect(Collectors.toSet()); Map<String, Integer> map = stream.collect(Collectors.toMap(String::toLowerCase, String::length));

toMap 用于将流中的元素转换为 Map。当存在重复键时,需要提供合并函数。例如:

Map<String, String> idToName = people.stream()

.collect(Collectors.toMap(Person::getId, Person::getName,

(existing, replacement) -> replacement));

此外,还可以使用 toUnmodifiableMap(Java 10+)创建不可变的 Map:

Map<String, String> unmodifiableMap = people.stream()

.collect(Collectors.toUnmodifiableMap(Person::getId, Person::getName));

toCollection() 允许指定具体的集合类型:

List<String> list = stream.collect(Collectors.toCollection(ArrayList::new)); Set<String> set = stream.collect(Collectors.toCollection(HashSet::new));

2. 分组与分区

groupingBy()进行分组并结合下游收集器

根据指定条件对元素进行分组,返回 Map

Map<String, List<Person>> peopleByCity = people.stream() .collect(Collectors.groupingBy(Person::getCity));

可以结合下游收集器进行统计:

例如,按条件分组并统计每组数量:

Map<String, Long> countByCity = people.stream() .collect(Collectors.groupingBy(Person::getCity, Collectors.counting()));

这种用法可以轻松实现类似 SQL 中 GROUP BY 的功能,并配合 counting()summingInt() 等下游收集器进行统计操作。

groupingBy()进行多级分组

可以通过嵌套使用 groupingBy 实现多级分组。例如,先按部门分组,再按职位分组:

Map<String, Map<String, List<Employee>>> byDeptAndPosition = employees.stream()

.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.groupingBy(Employee::getPosition)));

partitioningBy()进行二元分类

根据布尔条件将元素分为两组:

Map<Boolean, List<Person>> partitioned = people.stream() .collect(Collectors.partitioningBy(p -> p.getAge() >= 18));

也可以结合下游收集器,如统计每个分区的元素数量:

Map<Boolean, Long> counts = numbers.stream()

.collect(Collectors.partitioningBy(n -> n % 2 == 0, Collectors.counting()));

3. 聚合与统计

counting() 统计元素数量:

long count = stream.collect(Collectors.counting());

summingInt()summingLong()summingDouble()

对数值字段进行求和:

int total = people.stream().collect(Collectors.summingInt(Person::getAge));

averagingInt()averagingLong()averagingDouble()

计算平均值:

double average = people.stream().collect(Collectors.averagingInt(Person::getAge));

summarizingInt()

提供全面的统计信息(计数、总和、平均值、最大值、最小值):

IntSummaryStatistics stats = people.stream() .collect(Collectors.summarizingInt(Person::getAge));

4. 字符串连接

joining()

将流中的字符串元素连接成一个字符串:

String result = strings.stream().collect(Collectors.joining(", "));

5. reducing 实现归约操作

reducing()

执行自定义的归约操作:

Optional<Integer> sum = numbers.stream().collect(Collectors.reducing(Integer::sum));

reducing 用于对流中的元素进行归约操作,例如求和或查找最大值:

// 求和

int sum = numbers.stream()

.collect(Collectors.reducing(0, Integer::sum));

// 查找最长字符串

Optional<String> longest = words.stream()

.collect(Collectors.reducing((a, b) -> a.length() > b.length() ? a : b));

6. 后处理

collectingAndThen()

在收集完成后对结果进行处理:

List<String> immutableList = stream.collect(Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList));

7. 并发收集

groupingByConcurrent()

支持并发分组操作:

Map<String, List<Person>> concurrentGrouped = people.stream() .collect(Collectors.groupingByConcurrent(Person::getCity));

8. 统计信息收集

Collectors 提供了多种用于统计的收集器,如 summarizingIntsummarizingDouble 等,可以方便地计算总和、平均值、最大值、最小值等:

IntSummaryStatistics stats = students.stream()

.collect(Collectors.summarizingInt(Student::getScore));

9. 自定义收集器

可以通过 Collector 接口创建自定义收集器,实现特定的收集逻辑。

这些功能使得 Collectors 成为 Java Stream API 中处理数据聚合、分组和转换的强大工具。

相关推荐
RyFit36 分钟前
SpringAI 常见问题及解决方案大全
java·ai
石山代码1 小时前
C++ 内存分区 堆区
java·开发语言·c++
前端若水1 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
绝知此事1 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
无风听海1 小时前
C# 隐式转换深度解析
java·开发语言·c#
涛声依旧-底层原理研究所2 小时前
残差连接与层归一化通俗易懂的详解
人工智能·python·神经网络·transformer
一只大袋鼠2 小时前
Git 进阶(二):分支管理、暂存栈、远程仓库与多人协作
java·开发语言·git
csdn_aspnet2 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
fantasy_arch2 小时前
pytorch人脸匹配模型
人工智能·pytorch·python
熊猫_豆豆2 小时前
广义相对论水星近日点进动完整详细数学推导
python·天体·广义相对论