Question

I have a bunch of users that I've put into a list, then I have another set of a bunch of users I've added to a separate list. I am trying to compare the first list of objects to the second list and create a new list of the unique objects.

        // List creation (new, old, unique)
        List<User> listNew = new ArrayList<User>();
        List<User> listOld = new ArrayList<User>();
        List<User> listUnique = new ArrayList<User>();

  ...

   for (User unique : listNew) {
        if (!listOld.contains(unique)) {
            listUnique.add(unique);
        }
    }

So I have this code to do that, but it just duplicates the listNew. How could I compare objects to one another? My class file is

public class User {

    private String fName;
    private String mInitial;
    private String lName;
    private String age;
    private String city;
    private String state;

....
Was it helpful?

Solution 2

As other answers said, you need to override equals and hashCode.

You can use Collection.removeAll method.

First you need to wrap the listNew into a HasSet which ensure the uniquness.

Collection<User> newUniques = new HashSet<User>();
newUniques.addAll(listNew);
newUniques.removeAll(listOld);

Now your newUniques will have desired results.

If you can use the apache commons, ListUtils.removeAll(listNew, listOld) is another option.

OTHER TIPS

You need to implement equals and hashCode in the User class. If you don't have these methods implemented in User, listOld.contains(unique) will only return true if listOld contains exactly the same instance referenced by unique.

Check this out for the difference between identity and equality in java: What is the difference between identity and equality in OOP?

Sets have only unique elements by nature so that would be the correct type to use in your situation. First however you will need to properly override the hashcode() and equals() method of your User class. After that just try to add all instances to the a set and be done with it.

Set<User> uniqueUsers = new HashSet<User>();

for (User unique : listNew) {
    if (!listOld.contains(unique)) {
        uniqueUsers.add(unique);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top