复制代码

为懒人提供无限可能,生命不息,code不止

人类感性的情绪,让我们知难行难
我思故我在
日拱一卒,功不唐捐
  • 首页
  • 前端
  • 后台
  • 数据库
  • 运维
  • 资源下载
  • 实用工具
  • 接口文档工具
  • 登录
  • 注册

JAVA代码

【原创】java 对象或属性判重的几种方案

作者: 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();
	}
 
}