Android : Compare two ArrayList of objects and find unmatching ids from the second ArrayList

SKK picture SKK · Feb 18, 2015 · Viewed 18.5k times · Source

I want to compare two ArrayList of objects and find the unmatching values from the second ArrayList based on the ids in the object.

For Example:

Person.java

private int id;
private String name;
private String place;

MainActivity.java:

ArrayList<Person> arrayList1 = new ArrayList<Person>();
arrayList1.add(new Person(1,"name","place"));
arrayList1.add(new Person(2,"name","place"));
arrayList1.add(new Person(3,"name","place"));

ArrayList<Person> arrayList2 = new ArrayList<Person>();
arrayList2.add(new Person(1,"name","place"));
arrayList2.add(new Person(3,"name","place"));
arrayList2.add(new Person(5,"name","place"));
arrayList2.add(new Person(6,"name","place"));

I want to compare the arrayList1, arrayList2 and need to find the unmatching values from the arrayList2. I need the id values 5,6.

How can I do this?

Answer

Simas picture Simas · Feb 18, 2015

You can use an inner loop, to check if the Person's id from arrayList2 corresponds to any Person id in the arrayList1. You'll need a flag to mark if some Person was found.

ArrayList<Integer> results = new ArrayList<>();

// Loop arrayList2 items
for (Person person2 : arrayList2) {
    // Loop arrayList1 items
    boolean found = false;
    for (Person person1 : arrayList1) {
        if (person2.id == person1.id) {
            found = true;
        }
    }
    if (!found) {
        results.add(person2.id);
    }
}