简体   繁体   English

如何根据一个字段对数据列表进行分组

[英]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.

相关问题 如何根据另一个字段的条件从一个字段中拾取数据 - How to pick up data from one field based on the condition of another field 使用RXJava 2对数据分组,将元素添加到每个组并输出一个列表 - Group data with RXJava 2, add element to each group and output one list 如何基于Java中的ID对列表中的值进行分组? - How to group values in list based on id in java? 如何禁用基于一个字段的实体更新? - How disable entity updating based on one field? 如何在一个按钮中分组按钮列表? - How to group a list of buttons in one button? Kotlin:如何将列表中的字段 map 到新列表并将其分组 - Kotlin: How to map a field from list to a new list and group it 如何将数据从重复的列表数据转换为组数据列表 - how to convert data from duplicated list data to list of group data 如何过滤复杂对象列表,以便如果两个对象具有某个字段的值,我会根据条件删除一个 - How can I filter a List of complex objects so that if two have value for a field, I remove one based on criteria 基于字段的数据采样 - Data Sampling based on a field 如何根据内部列表的属性之一获取列表中的唯一元素 - How to get unique elements in list based on one of attribute of inner list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM