返回

java stream中的Collectors用法

闲谈

Java stream中的Collectors用法

在Java 8中,stream API是一个强大的工具,它可以帮助我们对数据进行高效的处理和转换。而Collectors类是stream API中一个非常重要的部分,它可以将stream转换成集合类,并提供各种聚合操作,如求和、求平均值、分组等。

一、Collectors简介

Collectors类提供了一系列静态方法,用于将stream转换为各种集合类,包括List、Set、Map等。它还提供了各种聚合操作,如summingInt()、averagingInt()、groupingBy()等。

二、Collectors用法示例

下面是一些Collectors的用法示例:

//stream转换成List
List<Integer> numbers = IntStream.range(1, 10).boxed().collect(Collectors.toList());

//stream转换成Set
Set<String> uniqueWords = Arrays.asList("hello", "world", "hello", "java").stream().collect(Collectors.toSet());

//stream转换成Map,其中key是单词,value是单词出现的次数
Map<String, Long> wordCounts = Arrays.asList("hello", "world", "hello", "java").stream()
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

//stream转换成Map,其中key是单词长度,value是单词列表
Map<Integer, List<String>> wordsByLength = Arrays.asList("hello", "world", "hello", "java").stream()
    .collect(Collectors.groupingBy(String::length, Collectors.toList()));

//stream转换成summary statistics
IntSummaryStatistics stats = IntStream.range(1, 10).summaryStatistics();

三、Collectors聚合操作

Collectors类还提供了一些聚合操作,这些操作可以将stream中的元素聚合为一个值。常用的聚合操作包括:

  • summingInt():计算stream中元素的总和。
  • averagingInt():计算stream中元素的平均值。
  • groupingBy():将stream中的元素根据某个字段分组。
  • counting():计算stream中元素的数量。

四、Collectors使用注意事项

在使用Collectors类时,需要注意以下几点:

  • Collectors类只能用于stream,不能用于其他集合类。
  • Collectors类的方法都是惰性的,这意味着它们不会立即执行。只有在调用stream的terminal操作时,Collectors类的方法才会执行。
  • Collectors类的方法都是幂等的,这意味着无论调用多少次,结果都是一样的。

总结

Collectors类是Java stream API中一个非常重要的部分,它可以将stream转换成集合类,并提供各种聚合操作。熟练掌握Collectors类的用法可以帮助我们更好地处理和分析数据。