如果我找对你,你需要一个List< Student> (不是地图)学生按其位置分组,并按组内的ID排序,组中的组也按ID排序,而不是按位置名称排序.这是可能的,但需要一个分组和两个排序:
//first,use your function to group students
Map> studlistGrouped = students.stream()
.collect(Collectors.groupingBy(Student::getLocation,Collectors.toList()));
//then sort groups by minimum id in each of them
List 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