Java8 集合分组

通过java8新特性 将一个list转换为一个list包含一个子list 子List也包含一个list的形式

private List<RecordExcelVO> convertExcel(List<ProjectDeclaration> projectList) {
        List<RecordExcelVO> list = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(projectList)) {
            // 按照备案日期分组
            Map<String, List<ProjectDeclaration>> firstGroup = projectList.stream().collect(Collectors.groupingBy(item -> DateFormatUtils.format(item.getRecordTime(), Constants.YEAR_MONTH)));

            for (Map.Entry<String, List<ProjectDeclaration>> first : firstGroup.entrySet()) {
                RecordExcelVO recordExcelVO = new RecordExcelVO();

                List<RecordExcelVO.CompanyVO> companies = new ArrayList<>();
                recordExcelVO.setMonth(first.getKey());
                recordExcelVO.setCompanies(companies);

                if (CollectionUtils.isNotEmpty(first.getValue())) {
                    // 按照建设单位分组
                    Map<String, List<ProjectDeclaration>> secondGroup = first.getValue().stream().collect(Collectors.groupingBy(item -> item.getCompanyName()));

                    for (Map.Entry<String, List<ProjectDeclaration>> second : secondGroup.entrySet()) {
                        RecordExcelVO.CompanyVO company = new RecordExcelVO.CompanyVO();
                        company.setCompanyName(second.getKey());
                        company.setProjects(second.getValue());

                        companies.add(company);
                    }
                }


                list.add(recordExcelVO);
            }
        }

        list = list.stream().sorted(Comparator.comparing(RecordExcelVO::getMonth)).collect(Collectors.toList());

        return list;
    }

猜你喜欢

转载自www.cnblogs.com/rain-in-summer/p/9207551.html