import java.util.*;
import java.util.stream.Collectors;
public class ListGroupingExample {
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)
);
// 使用stream API和Collectors.groupingBy对列表进行分组
Map<Integer, List<Person>> peopleGroupedByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
// 输出分组结果
peopleGroupedByAge.forEach((age, group) ->
System.out.println("Age " + age + ": " + group));
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return name;
}
}
Person
对象的列表,每个Person
对象都有一个名字和年龄。Collectors.groupingBy
方法,根据Person
对象的年龄属性对列表进行分组。分组后的结果是一个Map<Integer, List<Person>>
,其中键是年龄,值是具有相同年龄的Person
对象列表。Map
并打印出每个年龄对应的Person
对象列表。这段代码展示了如何使用Java的Stream API对列表中的元素进行分组。
上一篇:java字符串拼接
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站