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

前端 未结 6 1945
眼角桃花
眼角桃花 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:21

    This is simple. Override equal method in your User class. One very simple implementation(you can enhance it by using null checks etc) can be like below:

    @override
    public boolean equals(Object obj) {
    User other = (User) obj;
        if(this.id==other.id 
          && this.empCode.equals(other.empCode)
          && this.firstname.equals(other.firstname)
          && this.lastname.equals(other.lastname)
          && this.email.equals(other.email)){
              return true;
        }else{
            return false;
        }
    }
    

    Once done, you can use:

     for(user user: list1){
        if(!resultList.contains(user)){
           resultList.add(user);
        }
     }
    
    
     for(user user: list2){
        if(!resultList.contains(user)){
           resultList.add(user);
        }
     }
    

提交回复
热议问题