根据某些字段拆分对象列表



我需要根据某些字段的值对对象列表进行分组。

对于学生对象:

public class Student {
private int id;
private String section;
private Integer age;
private String city;
}

我有一份清单

List<Student> list = new ArrayList()<>;
list.add(new Student(1,"Biology", 23, "New York"));
list.add(new Student(2,"Mathematics", 22, "Chicago"));
list.add(new Student(3,"Technology", 23, "New York"));
list.add(new Student(4,"Biology", 23, "New York"));
list.add(new Student(5,"Technology", 23, "New York"));
list.add(new Student(6,"Biology", 21, "Chicago"));

我想把它分到具有相同部门/年龄/城市的列表中。

这意味着在我的例子中,我将有4个列表:(1和4(,2,(3和5(,6。

使用Streams有什么简单的方法吗?

使用Collectors.groupingBy并创建一个公共密钥。这将返回一个Map,该Map需要迭代才能获得组。

final Map<String, List<Student>> collect = list.stream()
.collect(Collectors.groupingBy(student -> String.format("%s:%d:%s", student.getSection(), student.getAge(), student.getCity())));
int group = 0;
for (Map.Entry<String, List<Student>> e : collect.entrySet()) {
System.out.println(++group + ": " + e.getValue());
}

1: [Student{id=1, section='Biology', age=23, city='New York'}, Student{id=4, section='Biology', age=23, city='New York'}]
2: [Student{id=3, section='Technology', age=23, city='New York'}, Student{id=5, section='Technology', age=23, city='New York'}]
3: [Student{id=6, section='Biology', age=21, city='Chicago'}]
4: [Student{id=2, section='Mathematics', age=22, city='Chicago'}]

最新更新