铁马冰河2000

导航

统计

JDK8流(stream)集合List常用分组或提取数据(List转Map,List转Set)

1、获取年龄>20的人员列表

List<User> list = users.stream().filter(item -> item.getAge() != null && item.getAge() > 20).collect(Collectors.toList());

2、以ID为Key,用户对象为Value构建Map(id为NULL时报错)

Map<Long, User> map = users.stream().collect(Collectors.toMap(User::getId, Function.identity()));

3、以ID为Key,deptId为Value构建Map(id或deptId为NULL时报错)

Map<Long, Long> map = users.stream().collect(Collectors.toMap(User::getId, User::getDeptId));

4、以deptId为Key进行分组(deptId为NULL时报错)

Map<Long, List<User>> map = users.stream().collect(Collectors.groupingBy(User::getDeptId));

5、提取ID 集合(List)

List<Long> ids = users.stream().map(User::getId).collect(Collectors.toList());

 6、提取部门ID集合(List)并去重

List<Long> deptIds = users.stream().map(User::getDeptId).distinct().collect(Collectors.toList());

7、提取部门ID集合(Set)

Set<Long> deptIds = users.stream().map(User::getDeptId).collect(Collectors.toSet());

 

posted on   铁马冰河2000  阅读(2874)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示