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

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

    I think this what you should do -

    for(User user1 : list1) {
        for(User user2 : list2) {
            if(user1.getEmpCode().equals(user2.getEmpCode())) {
                if(!user1.getFirstName().equals(user2.getFirstName()) ||
                   !user1.getLastName().equals(user2.getLastName()) ||
                   !user1.getEmail().equals(user2.getEmail())) {
                    resultList.add(user1);
                }
            }
        }
    }
    

    It might not make sense for the User to override equal and hashCode only to serve this purpose. They should be overriden in the way in which it makes more sense domain-wise.

提交回复
热议问题