List分组

List分组,第1张

List分组

1、需求描述:

        将List根据实体类属性分组

        现在存在queryProjectMemberList 如下

List queryProjectMemberList = projectMemberMapper.queryProjectMemberByProjectId(dataIds);

         ProjectMember中有属性projectId

        将queryProjectMemberList 根据projectId分组

        最后形式为 Map>

Map> projectMemberListMap = new HashMap<>();

2、解决方法:

        (1)java8新特性使用stream()分组

//分组后的map,一个projectId对应一个List
Map> projectMemberListMap = new HashMap<>();
//等待分组的集合
List queryProjectMemberList = projectMemberMapper.queryProjectMemberByProjectId(dataIds);
//分组 *** 作
projectMemberListMap= queryProjectMemberList.stream().collect(Collectors.groupingBy(ProjectMember::getProjectId));

        (2)java8之前的for循环分组

Map> projectMemberListMap = new HashMap<>();
List queryProjectMemberList = projectMemberMapper.queryProjectMemberByProjectId(dataIds);
//分组 *** 作
for (ProjectMember projectMember : queryProjectMemberList) {
   Integer projectId = projectMember.getProjectId();
   if (projectMemberListMap.containsKey(projectId)) {
      projectMemberListMap.get(projectId).add(projectMember);
   } else {
      List projectMemberList = new ArrayList<>();
      projectMemberList.add(projectMember);
      projectMemberListMap.put(projectId, projectMemberList);
   }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5434937.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存