Java List<T>去重方法,引用类型集合去重

2022-04-13 14:50:02 浏览数 (2)

一、实体类中要重写比较方法equals,最好也重写hashcode方法

代码语言:javascript复制
public class WorkWeightDto implements Serializable {

    private static final long serialVersionUID = 8245791221237374426L;

//    @Id  没有加id自增长策略 会影响到别的实体数据插入。
    private String id;
    private String projectId; // 项目Id
    private String projectName; // 项目    
    private String startTime; // 开始时间
    private String endTime; // 结束时间   
    private String managerId; // 负责人Id

    public WorkWeightDto() {
    }

    public WorkWeightDto(String id, String projectId, String startTime) {
        this.id = id;
        this.projectId = projectId;
        this.startTime = startTime;
    }

    @Override
    public boolean equals(Object o) {

        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        WorkWeightDto ww = (WorkWeightDto) o;
        if (id.equals(ww.getId()) && projectId.equals(ww.getProjectId()) && startTime.equals(ww.getStartTime())){
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return id.hashCode()   projectId.hashCode() startTime.hashCode();
    }

二、去重方法实现

代码语言:javascript复制
 private List<WorkWeightDto> deleteSame(List<WorkWeightDto> dtoList){

        Iterator<WorkWeightDto> it = dtoList.iterator();
        WorkWeightDto next =null;
        List<WorkWeightDto> newList = new ArrayList<WorkWeightDto>();
        while(it.hasNext()){
            next = it.next();
            if(!newList.contains(next)){
                newList.add(next);
            }
        }
        return  newList;
    }

三、其它方法参见:集合去重方法A 、 集合去重方法B

1 人点赞