java比较两个List中的不同元素 查找两个集合中的不同元素

public class Category {

    private int categId;
    private String categName;
    ....
    }

假设有这个集合, List<Category> metaCategs , 需要把categId 在下面数组中的category从metaCategs移除

Integer[] removeCategIds =new Integer[]{26395,12576,619,11700,100845,100850,100846};

一般想到的做法是循环metaCategs,分别取出categId和removeCategIds里面的每一个元素对比,如果相同,则从
集合metaCategs中移除.

这样一般要写两个循环才能完成.

另外一个比较优雅的做法是,重写Category的equals方法,如下:

public class Category {

    private int categId;
    private String categName;
    ....
    @Override
    public boolean equals(Object obj){
        if(obj instanceof Integer){
            if(this.getCategId()==(Integer)obj){
                return true;
            }else {
                return false;
            }
        }else{
            return  super.equals(obj);
        }
    }
    }

然后调用list的removeAll方法即可,如下:

List removeCategIdList = Arrays.asList(removeCategIds);
metaCategs.removeAll(removeCategIdList);

如果觉得本篇文章有所帮助,请帮忙微信扫描下本人写的一个实用小程序 “安全期随时看”,让你随时掌握爱爱时间,多谢帮助!
---------------------------在这里插入图片描述 -------------------------
-------------------------------------------安全期随时看---------------------------------------------

猜你喜欢

转载自blog.csdn.net/celebrateyang/article/details/89309919
今日推荐