Java List 对象属性分组:使用 Stream API 和 Collectors.groupingBy()
要根据对象属性分组,可以使用Java的Stream API和Collectors.groupingBy()方法。
假设有一个名为Person的类,有两个属性name和age,我们要根据age属性对Person对象进行分组。
1. 创建Person类
public 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;
}
}
2. 创建Person对象列表
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 20));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 20));
people.add(new Person("Dave", 25));
3. 使用Stream API和Collectors.groupingBy()方法进行分组
Map<Integer, List<Person>> groupByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
上述代码将根据age属性将Person对象列表分组,并将结果存储在一个Map中,其中key是age属性的值,value是具有相同age属性的Person对象列表。
4. 打印分组结果
groupByAge.forEach((age, group) -> {
System.out.println("Age: " + age);
group.forEach(person -> System.out.println(" " + person.getName()));
});
输出结果如下:
Age: 20
Alice
Charlie
Age: 25
Bob
Dave
这样,你就成功地根据对象属性进行了分组。
原文地址: https://www.cveoy.top/t/topic/eRY 著作权归作者所有。请勿转载和采集!