[英]How to group list of data based on one field
I have a list of custom class data, I want to group them based on one field and the value should be another field.我有一个自定义 class 数据列表,我想根据一个字段对它们进行分组,并且值应该是另一个字段。 Take the example below.
举个例子。
List<Student> list = new ArrayList<>();
list.add(new Student(1001, "Class 1", "Jon"));
list.add(new Student(1002, "Class 1", "Eliana"));
list.add(new Student(1003, "Class 2", "Piter"));
list.add(new Student(1004, "Class 3", "Joy"));
list.add(new Student(1005, "Class 2", "Anderson"));
list.add(new Student(1006, "Class 1", "Ram"));
list.add(new Student(1007, "Class 1", "Mohan"));
Now I would like to group this data based on class.现在我想根据 class 对这些数据进行分组。 The expected output should be a map containing key as the class and value as the list of student names.
预期的 output 应该是 map,其中包含作为 class 的键和作为学生姓名列表的值。
{"Class 1" -> ["Jon", "Eliana", "Ram", "Mohan"]}
{"Class 2" -> ["Piter", "Anderson"]}
{"Class 3" -> ["Joy"]}
I want to get this using java 8 stream feature.我想使用 java 8 stream 功能来获得这个。 I tried doing this and I could group the whole object into a map as the key being the class name and value is a list of students.
我尝试这样做,我可以将整个 object 分组到 map 中,因为键是 class 名称和值是学生列表。 But my requirement is to get value as the only a list of student names.
但我的要求是获得价值作为唯一的学生姓名列表。
My pice of code is something like this:我的代码是这样的:
list.stream().collect(Collectors.groupingBy(Students::getClass));
From the above comments section, it can be done in this way:从上面的评论部分,可以通过这种方式完成:
Map<EligibilityRequest, List<List<String>>> result =
list.stream()
.collect(Collectors.groupingBy(Student::getClass,
Collectors.mapping(Student::getName, toList())
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.