How to compare two array lists for similar objects which differ in at least one property in java?

前端 未结 6 1946
眼角桃花
眼角桃花 2021-01-07 01:03

I have two array list. Each has list of Objects of type User.

The User class looks like below

    public class User {

    private long id;

    pri         


        
6条回答
  •  被撕碎了的回忆
    2021-01-07 01:31

    Implement equals, hashcode in User

        @Override
        public boolean equals(Object obj) {
            if (obj == null)
                return false;
            if (!(obj instanceof User))
                return false;
            User u = (User) obj;
            return this.empCode == null ? false : this.empCode
                    .equals(u.empCode);
        }
    
        @Override
        public int hashCode() {
            return this.empCode == null ? 0 : this.empCode.hashCode();
        }
    
        @Override
        public String toString() {
            return "Emp Code: " + this.empCode;
        }
    

    Then use retainAll

    list2.retainAll(list1);-->EMP01, EMP02, EMP09, EMP10
    

提交回复
热议问题