基于以下答案:
https://stackoverflow.com/a/30202075/8760211
如何通过stud_id对每个组进行排序,然后通过stud_location返回一个包含所有学生的List作为分组的结果,然后按stud_id排序?
将它作为现有Lambda表达式的扩展会很棒:
- Map<String,List<Student>> studlistGrouped =
- studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
我需要基于原始列表中元素的顺序进行分组.
- First group: "New York"
- Second group: "California"
- Third group: "Los Angeles"
- 1726,"John","New York"
- 4321,"Max","California"
- 2234,"Andrew","Los Angeles"
- 5223,"Michael","New York"
- 7765,"Sam","California"
- 3442,"Mark","New York"
结果将如下所示:
- List<Student> groupedAndSorted = ....
- 1726,"New York"
- 3442,"New York"
- 5223,"New York"
- 4321,"California"
- 7765,"California"
- 2234,"Los Angeles"
我尝试过以下方法:
- studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
但这不起作用.
解决方法
如果我找对你,你需要一个List< Student> (不是地图)学生按其位置分组,并按组内的ID排序,组中的组也按ID排序,而不是按位置名称排序.这是可能的,但需要一个分组和两个排序:
- //first,use your function to group students
- Map<String,List<Student>> studlistGrouped = students.stream()
- .collect(Collectors.groupingBy(Student::getLocation,Collectors.toList()));
- //then sort groups by minimum id in each of them
- List<Student> sorted = studlistGrouped.entrySet().stream()
- .sorted(Comparator.comparing(e -> e.getValue().stream().map(Student::getId).min(Comparator.naturalOrder()).orElse(0)))
- //and also sort each group before collecting them in one list
- .flatMap(e -> e.getValue().stream().sorted(Comparator.comparing(Student::getId))).collect(Collectors.toList());
这将产生以下结果:
- Student{id='1726',name='John',location='New York'}
- Student{id='3442',name='Mark',location='New York'}
- Student{id='5223',name='Michael',location='New York'}
- Student{id='2234',name='Andrew',location='Los Angeles'}
- Student{id='4321',name='Max',location='California'}
- Student{id='7765',name='Sam',location='California'}
也许这可以更优雅地完成,欢迎提出建议
编辑:在写这个答案的时候,没有提到基于OPs问题中原始列表中元素顺序的分组.所以我的假设是按ID分类列表和组.对于基于原始列表中的顺序的解决方案,请参阅其他答案,例如,Holgers one