在Java中如何使用Collectors收集流结果

Collectors是Java中用于将流元素收集到集合或进行聚合操作的工具类,提供toList、toSet、toMap实现数据收集与转换,支持分组groupingBy、分区partitioningBy、统计counting、求和summingInt及字符串连接joining等功能,极大简化数据处理。

在Java中,Collectorsjava.util.stream.Collectors 类提供的工具集合,用于将流(Stream)中的元素收集到目标容器中,比如 List、Set、Map,或者进行分组、分区、拼接等操作。它是函数式编程中非常实用的组件。

收集到集合中

最常见的用途是把流中的元素收集到集合类型中:

  • Collectors.toList():收集为 ArrayList
  • Collectors.toSet():收集为 HashSet,自动去重
  • Collectors.toCollection(集合构造器):指定具体集合类型
示例:
List names = people.stream()
    .map(Person::getName)
    .collect(Collectors.toList());

Set uniqueNames = people.stream()
    .map(Person::getName)
    .collect(Collectors.toSet());

// 收集到 LinkedList
LinkedList linkedList = stream.collect(
    Collectors.toCollection(LinkedList::new)
);

转换为 Map

使用 Collectors.toMap() 可以将流中的元素转为 Map,需提供键和值的映射函数。

Map idToName = people.stream()
    .collect(Collectors.toMap(
        Person::getId,
        Person::getName
  

));

如果存在重复 key,会抛出异常。此时可传入第四个参数(合并函数)解决冲突:

Map idToName = people.stream()
    .collect(Collectors.toMap(
        Person::getId,
        Person::getName,
        (existing, replacement) -> existing  // 保留第一个
    ));

分组与分区

Collectors.groupingBy() 按条件分组,返回一个 Map,key 是分组依据。

// 按年龄分组
Map> byAge = people.stream()
    .collect(Collectors.groupingBy(Person::getAge));

// 多级分组:先按年龄,再按性别
Map>> groupByAgeAndGender = people.stream()
    .collect(Collectors.groupingBy(
        Person::getAge,
        Collectors.groupingBy(Person::getGender)
    ));

Collectors.partitioningBy() 是特殊的分组,只分为两组:true 和 false。

// 按是否成年分区
Map> adultPartition = people.stream()
    .collect(Collectors.partitioningBy(p -> p.getAge() >= 18));

聚合与统计

Collectors 提供了多种聚合操作:

  • Collectors.counting():计数
  • Collectors.summingInt():对 int 值求和
  • Collectors.averagingDouble():求平均值
  • Collectors.maxBy()/minBy():获取最大/最小值
  • Collectors.summarizingInt():生成统计信息(总数、总和、平均、最大、最小)
示例:
Long count = people.stream()
    .collect(Collectors.counting());

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

int maxAge = people.stream()
    .collect(Collectors.maxBy(Comparator.comparing(Person::getAge)))
    .map(Person::getAge)
    .orElse(0);

字符串连接

使用 Collectors.joining() 将字符串拼接起来,支持分隔符、前缀和后缀。

String names = people.stream()
    .map(Person::getName)
    .collect(Collectors.joining(", ", "Names: ", "."));

// 输出示例:Names: Alice, Bob, Charlie.
基本上就这些常用方式。根据实际需求组合使用,能极大简化数据处理逻辑。