Set集合对象去重
只有实现,没有原理。通过重写类的hashCode()跟equals()方法来实现,当前者返回的hashCode相同并且equals()方法返回true时,则判断为重复
一般hashCode()方法返回的是主键id.hashCode(),或者多个属性的混合编码
equals()方法里多判断各个属性值是否相同
实体类
@Data
@Builder(toBuilder = true)
public class SysDeptTree extends BaseEntity {
private String name;
private String parentId;
private SysDeptTree children;
private Long id;
@Override
public int hashCode(){
return this.name.hashCode();
}
@Override
public boolean equals(Object object){
SysDeptTree sysDeptTree = (SysDeptTree)object;
return this.name.equals(sysDeptTree.name);
}
@Override
public String toString(){
return "name = "+this.name;
}
}
使用
@GetMapping("/area")
public AjaxResult area() {
List<SysDept> depts = deptService.selectDeptList(new SysDept());
Set<SysDeptTree> set = new HashSet<SysDeptTree>();
for (SysDept dept:depts) {
set.add(SysDeptTree.builder().name(dept.getProvince()).parentId("0").build());
set.add(SysDeptTree.builder().name(dept.getCity()).parentId(dept.getProvince()).build());
set.add(SysDeptTree.builder().name(dept.getArea()).parentId(dept.getCity()).build());
set.add(SysDeptTree.builder().name(dept.getDeptName()).id(dept.getDeptId()).parentId(dept.getArea()).build());
}
return AjaxResult.success(set);
}