作者: whooyun发表于: 2023-03-09 17:23
判断List<?>对象是否存在相同属性的数据,并留下不重复的属性
List<AcvGdsUnitVO> acvGdsUnitVOList = new ArrayList(); List<String> duplicateList = acvGdsUnitVOList.stream().map(AcvGdsUnitVO::getName).distinct().collect(Collectors.toList()); if(duplicateList.size < acvGdsUnitVOList.size){ log.debug("存在重复数据"); }判断List<?>对象是否存在相同属性的数据,并留下不重复的对象
ArrayList<AcvGdsUnitVO> duplicateList = acvGdsUnitVOList.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(AcvGdsUnitVO::getName))), ArrayList::new));// 根据map去重
Map<String, AcvGdsUnitVO> map = new HashMap<>(); for (AcvGdsUnitVO unitVO : acvGdsUnitVOList) { String name = unitVO.getName(); if (!map.containsKey(name)){ map.put(name,unitVO); } } List<AcvGdsUnitVO> duplicateList = new ArrayList<>(); for (String name : map.keySet()) { duplicateList.add(map.get(name)); }//重写AcvGdsUnitVO对象的equals和hashCode方法,再使用Set去重
Set<AcvGdsUnitVO> acvGdsUnitVOSet = new HashSet<>(acvGdsUnitVOList); List<AcvGdsUnitVO> duplicateList = new ArrayList<>(acvGdsUnitVOSet); public class AcvGdsUnitVO { private Integer reqFlag; private Long reqId; private Long id; private String unitNo; private String name; private String remark; private Integer statusDic; private LocalDateTime createDtm; private LocalDateTime modifiedDtm; private Integer corpId; private Integer orgId; private Integer isDeleted; // 重写equals和hashCode方法 @Override public boolean equals(Object o) { AcvGdsUnitVO vo = (AcvGdsUnitVO) o; return this.name.equals(vo.getName()); } @Override public int hashCode() { return this.name.hashCode(); } }