1、需求描述:
将List根据实体类属性分组
现在存在queryProjectMemberList 如下
ListqueryProjectMemberList = projectMemberMapper.queryProjectMemberByProjectId(dataIds);
ProjectMember中有属性projectId
将queryProjectMemberList 根据projectId分组
最后形式为 Map
Map> projectMemberListMap = new HashMap<>();
2、解决方法:
(1)java8新特性使用stream()分组
//分组后的map,一个projectId对应一个ListMap > 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); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)