前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java List<T>去重方法,引用类型集合去重

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

作者头像
微风-- 轻许--
发布2022-04-13 14:50:02
1.3K0
发布2022-04-13 14:50:02
举报
文章被收录于专栏:java 微风java 微风

一、实体类中要重写比较方法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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/01/09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档