Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two object arraylists

Tags:

java

First time here so I hope this makes sense!

I have two object arrays say l1 and l2, I want to run a compare between these two lists and get a the unmatched value in say in l3. User class contains 2 Strings:

userEnteredValue 
valueReturnedFromDatabase

Say, l1 contains: Java, JSF, JAXR, foo l2 contains: JSF, JAXR

I could run a compare for matching values, but for not for non-matching values. The logic seems to be flawed. Any help?

For matching values:

for(User u1 : l1) {
   for(User u2: l2) { 
      if(u1.getUserEnteredValue().equals(u2.getValueReturnedFromDatabase())) {
        l3.add(u1);
      }
} 

But, for the non-matching when I say not equal to, instead of getting only the unique values I get all values. A couple of similar posts on Stackoverflow suggest to implement the equals and hashcode method in the User class. Is this necessary, since my arraylist size don't go beyond 5 to 10.

like image 320
Ani Avatar asked Aug 17 '26 18:08

Ani


1 Answers

You can do something like this:

for(User u1 : l1) {
    boolean unique = true;
    for(User u2: l2) { 
        if(u1.getUserEnteredValue().equals(u2.getValueReturnedFromDatabase())) {
            unique = false;
            break;
        }
    } 
    if(unique){
        l3.add(u1);
    }
}
like image 161
Titus Avatar answered Aug 20 '26 10:08

Titus