在现代Java开发中,Stream API 已经
成为一个强大的工具,它提供了一种简洁而灵活的方式来处理集合数据。其中,Stream API 统计、汇总、多字段分组和多个列汇总统计是使用频率较高的功能。本文将深入介绍这些功能,并提供一些代码示例。
一、统计功能:
示例代码:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
long count = numbers.stream().count();
Optional<Integer> max = numbers.stream().max(Integer::compareTo);
Optional<Integer> min = numbers.stream().min(Integer::compareTo);
double average = numbers.stream().mapToInt(Integer::intValue).average().orElse(0);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
二、汇总功能:
示例代码:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> sum = numbers.stream().reduce(Integer::sum);
List<Integer> squaredNumbers = numbers.stream().map(n -> n * n).collect(Collectors.toList());
Set<Integer> evenNumbers = numbers.stream().filter(n -> n % 2 == 0).collect(Collectors.toSet());
Map<String, List<Integer>> groupByOddEven = numbers.stream().collect(Collectors.groupingBy(n -> n % 2 == 0 ? "Even" : "Odd"));
三、多字段分组:
使用 Collectors.groupingBy
方法可以实现对流中元素的多字段分组。
示例代码:
class Person {
private String name;
private int age;
private String gender;
// 省略构造函数和 Getter/Setter 方法
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
List<Person> people = Arrays.asList(
new Person("Alice", 20, "Female"),
new Person("Bob", 30, "Male"),
new Person("Charlie", 25, "Male"),
new Person("David", 22, "Male"),
new Person("Eva", 28, "Female"),
new Person("Frank", 35, "Male")
);
Map<String, List<Person>> byGender = people.stream().collect(Collectors.groupingBy(Person::getGender));
Map<Integer, List<Person>> byAge = people.stream().collect(Collectors.groupingBy(Person::getAge));
四、多个列汇总统计:
使用 Collectors.groupingBy
方法结合 Collectors.summarizingInt
方法可以实现对流中元素的多个列进行汇总统计。
示例代码:
class Product {
private String category;
private String name;
private int price;
private int quantity;
// 省略构造函数和 Getter/Setter 方法
@Override
public String toString() {
return "Product{" +
"category='" + category + '\'' +
", name='" + name + '\'' +
", price=" + price +
", quantity=" + quantity +
'}';
}
}
List<Product> products = Arrays.asList(
new Product("Electronics", "Laptop", 2500, 5),
new Product("Electronics", "Phone", 800, 3),
new Product("Clothing", "Shirt", 40, 10),
new Product("Clothing", "Pants", 60, 8),
new Product("Books", "Java in Action", 50, 15),
new Product("Books", "Clean Code", 80, 12)
);
Map<String, IntSummaryStatistics> statsByCategory = products.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.summarizingInt(Product::getQuantity)