8

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?

SKK
  • 1,705
  • 3
  • 28
  • 50

4 Answers4

20

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);
    }
}
Simas
  • 43,548
  • 10
  • 88
  • 116
3

Look at the modifications to person class

public static class Person{

        //setters and getters

        @Override
        public boolean equals(Object other) {
            if (!(other instanceof Person)) {
                return false;
            }

            Person that = (Person) other;

            // Custom equality check here.
            return this.getId() == that.getId();
        }

    }

Have overridden equals(Object other)

then simply do this

for (Person person : arrayList1) {
            arrayList2.remove(person);
}

your answer is array list 2, it will only contain odd objects

Prateek Thakur
  • 179
  • 1
  • 5
0

You should iterate through the shortest ArrayList you have, so check which list is shorter and then iterate through all the indexes in that list against every index in the other list.

(This is assuming you don't have any duplicates in either list. If you do, you might want to return a list of all indexes found.)

Bam
  • 478
  • 6
  • 19
-1

arrayListChars=new ArrayList<>(); //[M,A,R,V,E,L]

arrayListAddChars=new ArrayList<>(); //[M,A,....coming values]

int count = 0;

for(int i=0;i

if(arrayListAddChars.get(i).equals(arrayListChars.get(i))){

    count++;
   }
    else
    {
     break;
    }
  }
Rahul Singh
  • 320
  • 4
  • 7