我找到了通过POJO中的某些字段名称对对象进行分组的代码。以下是该代码:
public class Temp {
static class Person {
private String name;
private int age;
private long salary;
Person(String name, int age, long salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public String toString() {
return String.format("Person{name='%s', age=%d, salary=%d}", name, age, salary);
}
}
public static void main(String[] args) {
Stream<Person> people = Stream.of(new Person("Paul", 24, 20000),
new Person("Mark", 30, 30000),
new Person("Will", 28, 28000),
new Person("William", 28, 28000));
Map<Integer, List<Person>> peopleByAge;
peopleByAge = people
.collect(Collectors.groupingBy(p -> p.age, Collectors.mapping((Person p) -> p, toList())));
System.out.println(peopleByAge);
}
}
输出是(正确的):
{24=[Person{name='Paul', age=24, salary=20000}], 28=[Person{name='Will', age=28, salary=28000}, Person{name='William', age=28, salary=28000}], 30=[Person{name='Mark', age=30, salary=30000}]}
但是,如果我想按多个字段分组怎么办?在该POJO中groupingBy()实现equals()方法后,我显然可以在该方法中传递一些POJO,但是是否还有其他选择,例如我可以对给定POJO中的多个字段进行分组?
例如,在这里,我想按姓名和年龄分组。
长风秋雁
蓝山帝景
慕斯王
相关分类