import java.util.*;
import java.util.stream.Collectors;
public class GroupByExample {
public static void main(String[] args) {
// 创建一个包含多个Person对象的列表
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 30),
new Person("David", 25)
);
// 使用Java Lambda表达式和Stream API对年龄进行分组
Map<Integer, List<Person>> peopleGroupedByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
// 输出分组结果
peopleGroupedByAge.forEach((age, group) ->
System.out.println("Age " + age + ": " + group.stream().map(Person::getName).collect(Collectors.toList()))
);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Person 对象的列表,每个 Person 对象有两个属性:name 和 age。stream() 方法将列表转换为流,并通过 Collectors.groupingBy() 方法根据 Person 对象的 age 属性进行分组。groupingBy 接受一个函数作为参数,这里我们使用了方法引用 Person::getAge 来获取每个人的年龄。Map,并输出每个年龄组中的人的名字。这段代码展示了如何使用 Java Lambda 表达式和 Stream API 来对集合中的元素进行分组。
上一篇:base64 java
下一篇:java stopwatch用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站