美文网首页
java stream流常用操作记录

java stream流常用操作记录

作者: 南瓜pump | 来源:发表于2022-03-11 09:44 被阅读0次

1.获取集合中对象的某个字段的集合(使用Set接收可以去重)

List<User> userList = userService.list();
Set<String> userIdList = userList .stream().map(User::getId).collect(Collectors.toSet());

2.使用集合对象的某个字段生成map映射,方便根据id获取对象,比如根据用户id获取用户信息;

Map<String, User> userMapById = userList .stream().collect(Collectors.toMap(User::getId, x -> x));

3.使用集合对象的某个字段将集合分组,方便根据该字段获取到对应的集合,比如根据用户id获取该用户的角色关联信息;

Map<String, List<UserRoleRef>> userRoleRefMapByUserId = userRoleRefList .stream().collect(Collectors.groupingBy(User::getId));

相关文章

网友评论

      本文标题:java stream流常用操作记录

      本文链接:https://www.haomeiwen.com/subject/kejfdrtx.html