Java8去重
package com.cdyfsz.autoaudit.rule.tool.test; import com.cdyfsz.autoaudit.rule.tool.dto.ExcelAuditConclusionDto; import com.cdyfsz.autoaudit.rule.tool.utils.CollectionUtils; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toCollection; public class testMain01 { public static void main(String[] args) { List<ExcelAuditConclusionDto> auditConclusionCodeList = new ArrayList<>(); ExcelAuditConclusionDto excelAuditConclusionDto1 = new ExcelAuditConclusionDto(); excelAuditConclusionDto1.setAuditConclusionCode("01"); excelAuditConclusionDto1.setAuditConclusion("结论1"); excelAuditConclusionDto1.setAuditConclusionParentCode("001"); ExcelAuditConclusionDto excelAuditConclusionDto2 = new ExcelAuditConclusionDto(); excelAuditConclusionDto2.setAuditConclusionCode("01"); excelAuditConclusionDto2.setAuditConclusion("结论1"); excelAuditConclusionDto2.setAuditConclusionParentCode("001"); ExcelAuditConclusionDto excelAuditConclusionDto3 = new ExcelAuditConclusionDto(); excelAuditConclusionDto3.setAuditConclusionCode("02"); excelAuditConclusionDto3.setAuditConclusion("结论2"); excelAuditConclusionDto3.setAuditConclusionParentCode("002"); auditConclusionCodeList.add(excelAuditConclusionDto1); auditConclusionCodeList.add(excelAuditConclusionDto2); auditConclusionCodeList.add(excelAuditConclusionDto3); if (CollectionUtils.isNotEmpty(auditConclusionCodeList)) { // 去重 auditConclusionCodeList = auditConclusionCodeList.stream().collect(collectingAndThen( toCollection(() -> new TreeSet<>(Comparator.comparing(ExcelAuditConclusionDto::getAuditConclusionCode))), ArrayList::new) ); auditConclusionCodeList = auditConclusionCodeList.stream().collect(collectingAndThen( toCollection(()-> new TreeSet<>(Comparator.comparing(ExcelAuditConclusionDto::getAuditConclusionCode))),ArrayList::new) ); // 去重 auditConclusionCodeList = auditConclusionCodeList.stream().filter(distinctByKey(ExcelAuditConclusionDto::getAuditConclusionCode)).collect(Collectors.toList()); } for (ExcelAuditConclusionDto rd :auditConclusionCodeList){ System.out.println(rd.getAuditConclusionCode()+"====="+rd.getAuditConclusion()); } } private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { Set<Object> seen = ConcurrentHashMap.newKeySet(); return t -> seen.add(keyExtractor.apply(t)); } }