有的时候博客内容会有变动,首发博客是最新的,其他博客地址可能会未同步,认准
https://blog.zysicyj.top
Java 8 引入的 Stream API 提供了强大的聚合操作,可以方便地对集合进行操作,如过滤、映射、归约和收集等。下面将详细介绍如何使用 Java Stream 的聚合功能,并通过具体示例进行演示。
Stream 的基本聚合操作
1. filter
用于过滤流中的元素,保留符合条件的元素。
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
System.out.println(filteredNames); // 输出: [Alice]
2. map
用于将流中的元素映射到另外一个元素,通常用于转换操作。
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<Integer> nameLengths = names.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println(nameLengths); // 输出: [5, 3, 7, 5]
3. reduce
用于将流中的元素反复结合起来,得到一个值。常用于求和、乘积、连接字符串等操作。
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, Integer::sum);
System.out.println(sum); // 输出: 15
聚合操作的高级用法
1. 分组 groupingBy
将流中的元素按照某个分类函数进行分类,结果是一个 Map。
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Anna");
Map<Character, List<String>> groupedByFirstLetter = names.stream()
.collect(Collectors.groupingBy(name -> name.charAt(0)));
System.out.println(groupedByFirstLetter);
// 输出: {A=[Alice, Anna], B=[Bob], C=[Charlie], D=[David]}
2. 分区 partitioningBy
将流中的元素按照给定的谓词进行分区,结果是一个包含两个列表的 Map,一个是满足谓词的元素,另一个是不满足谓词的元素。
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println(partitioned);
// 输出: {false=[1, 3, 5], true=[2, 4, 6]}
3. 统计 summarizingInt, summarizingDouble, summarizingLong
对流中的元素进行统计,结果是一个包含统计信息的对象,例如数量、总和、最小值、平均值和最大值。
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer::intValue));
System.out.println(stats);
// 输出: IntSummaryStatistics{count=6, sum=21, min=1, average=3.500000, max=6}
4. 收集到集合 toList, toSet, toMap
将流中的元素收集到不同类型的集合中。
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Alice");
Set<String> nameSet = names.stream()
.collect(Collectors.toSet());
System.out.println(nameSet); // 输出: [Alice, Bob, Charlie, David]
Map<String, Integer> nameLengthMap = names.stream()
.distinct()
.collect(Collectors.toMap(name -> name, String::length));
System.out.println(nameLengthMap); // 输出: {Alice=5, Bob=3, Charlie=7, David=5}
完整示例
以下是一个使用 Stream API 进行聚合操作的完整示例:
import java.util.*;
import java.util.stream.*;
public class StreamAggregationExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Anna");
// 过滤
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
System.out.println("Filtered Names: " + filteredNames);
// 映射
List<Integer> nameLengths = names.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println("Name Lengths: " + nameLengths);
// 归约
int totalLength = names.stream()
.map(String::length)
.reduce(0, Integer::sum);
System.out.println("Total Length of All Names: " + totalLength);
// 分组
Map<Character, List<String>> groupedByFirstLetter = names.stream()
.collect(Collectors.groupingBy(name -> name.charAt(0)));
System.out.println("Grouped By First Letter: " + groupedByFirstLetter);
// 分区
Map<Boolean, List<String>> partitionedByLength = names.stream()
.collect(Collectors.partitioningBy(name -> name.length() > 3));
System.out.println("Partitioned By Length > 3: " + partitionedByLength);
// 统计
IntSummaryStatistics stats = names.stream()
.collect(Collectors.summarizingInt(String::length));
System.out.println("Statistics: " + stats);
// 收集到 Set
Set<String> nameSet = names.stream()
.collect(Collectors.toSet());
System.out.println("Names as Set: " + nameSet);
// 收集到 Map
Map<String, Integer> nameLengthMap = names.stream()
.distinct()
.collect(Collectors.toMap(name -> name, String::length));
System.out.println("Names and Their Lengths: " + nameLengthMap);
}
}
总结
Java 8 的 Stream API 提供了强大的聚合操作,可以方便地对集合进行各种复杂的操作,包括过滤、映射、归约、分组和统计等。通过掌握这些操作,可以编写出简洁、高效且易于维护的代码。
本文是原创文章,采用 CC BY-NC-SA 4.0 协议,完整转载请注明来自 小朱
评论
隐私政策
0/500
滚动到此处加载评论...


