Collectors类提供丰富静态方法将流元素收集到集合、Map或数值结果中,如toList()、toSet()、toMap()实现集合转换,groupingBy()和partitioningBy()支持分组与分区,counting()、summarizingInt()等用于聚合统计,joining()可拼接字符串,结合lambda提升代码可读性。
Java中的Collectors类是java.util.stream.Collectors的工具类,用于将流(Stream)中的元素收集到目标容器中,比如集合、字符串或数值结果。它提供了丰富的静态方法来支持常见的归约操作,是流式编程中不可或缺的一部分。
最常见的是把流中的元素收集为List、Set或Map。
例如:Listlist = Stream.of("a", "b", "c").collect(Collectors.toList()); Set set = Stream.of(1, 2, 2, 3).collect(Collectors.toSet());
使用toMap可以将流中的对象转换为键值对形式的Map。
Mapmap = list.stream() .collect(Collectors.toMap( Person::getId, Person::get Name, (existing, replacement) -> existing // 冲突时保留旧值 ));
Collectors支持按条件对数据进行分类。
Map> byDept = people.stream() .collect(Collectors.groupingBy(Person::getDepartment)); Map > evenOdd = numbers.stream() .collect(Collectors.partitioningBy(n -> n % 2 == 0));
可用于计算总和、平均值、计数等。
long count = list.stream().collect(Collectors.counting()); double avgAge = users.stream().collect(Collectors.averagingDouble(User::getAge)); IntSummaryStatistics stats = numbers.stream().collect(Collectors.summarizingInt(x -> x));
对于字符串流,可以用joining拼接内容。
String joined = Stream.of("a", "b", "c")
.collect(Collectors.joining(", ", "[", "]"));
// 输出: [a, b, c]
基本上就这些常见用法。Collectors让流的结果处理变得简洁高效,结合lambda表达式可大幅提升代码可读性。根据实际需求选择合适的收集方式即可。