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

如果我找对你,你需要一个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值