Java 8,Lambda:在分组列表中排序并将所有组合并到列表中

前端之家收集整理的这篇文章主要介绍了Java 8,Lambda:在分组列表中排序并将所有组合并到列表中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基于以下答案: https://stackoverflow.com/a/30202075/8760211

如何通过stud_id对每个组进行排序,然后通过stud_location返回一个包含所有学生的List作为分组的结果,然后按stud_id排序?

将它作为现有Lambda表达式的扩展会很棒:

  1. Map<String,List<Student>> studlistGrouped =
  2. studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

我需要基于原始列表中元素的顺序进行分组.

  1. First group: "New York"
  2. Second group: "California"
  3. Third group: "Los Angeles"
  4.  
  5. 1726,"John","New York"
  6. 4321,"Max","California"
  7. 2234,"Andrew","Los Angeles"
  8. 5223,"Michael","New York"
  9. 7765,"Sam","California"
  10. 3442,"Mark","New York"

结果将如下所示:

  1. List<Student> groupedAndSorted = ....
  2.  
  3. 1726,"New York"
  4. 3442,"New York"
  5. 5223,"New York"
  6. 4321,"California"
  7. 7765,"California"
  8. 2234,"Los Angeles"

我尝试过以下方法

  1. studlistGrouped.entrySet().stream().sorted(Comparator.compar‌​ing(Map.Entry::getVa‌​lue))

但这不起作用.

解决方法

如果我找对你,你需要一个List< Student> (不是地图)学生按其位置分组,并按组内的ID排序,组中的组也按ID排序,而不是按位置名称排序.这是可能的,但需要一个分组和两个排序:
  1. //first,use your function to group students
  2. Map<String,List<Student>> studlistGrouped = students.stream()
  3. .collect(Collectors.groupingBy(Student::getLocation,Collectors.toList()));
  4.  
  5. //then sort groups by minimum id in each of them
  6. List<Student> sorted = studlistGrouped.entrySet().stream()
  7. .sorted(Comparator.comparing(e -> e.getValue().stream().map(Student::getId).min(Comparator.naturalOrder()).orElse(0)))
  8. //and also sort each group before collecting them in one list
  9. .flatMap(e -> e.getValue().stream().sorted(Comparator.comparing(Student::getId))).collect(Collectors.toList());

这将产生以下结果:

  1. Student{id='1726',name='John',location='New York'}
  2. Student{id='3442',name='Mark',location='New York'}
  3. Student{id='5223',name='Michael',location='New York'}
  4. Student{id='2234',name='Andrew',location='Los Angeles'}
  5. Student{id='4321',name='Max',location='California'}
  6. Student{id='7765',name='Sam',location='California'}

也许这可以更优雅地完成,欢迎提出建议

编辑:在写这个答案的时候,没有提到基于OPs问题中原始列表中元素顺序的分组.所以我的假设是按ID分类列表和组.对于基于原始列表中的顺序的解决方案,请参阅其他答案,例如,Holgers one

猜你在找的Java相关文章