Java How to compare results of 2 ArrayList or iterators

Vikas J :

I have a requirement to compare the results of 2 ArrayList which do not have the same number of values. So for instance list_SrcColumnDetails will contain 10 values and list_userEnteredfieldName will contain 2 values. Now in list_userEnteredfieldName out of 2 values, only 1 exists in list_SrcColumnDetails.

So I want to display in the result which value is matching and which does not. I tried comparing ArrayLists but as per my knowledge for comparing ArrayLists number of values needs to be the same. So I used Iterator but it's not working as expected. Any help on how I can compare values at each index either by ArrayList or Iterator?

List<String> list_SrcColumnDetails = new ArrayList <String>();   // Id,Name,Adress,.....upto 10 values
List<String> list_userEnteredfieldName = new ArrayList <String>(); // Id,Text . Text does not exists in list_SrcColumnDetails
Iterator<String> user_iterator1 = list_userEnteredfieldName.iterator();
Iterator<String> Src_iterator2 = list_SrcColumnDetails.iterator();
while(user_iterator1.hasNext()){

              if (user_iterator1.next().equals(Src_iterator2.next()))
              {
                  System.out.println("User Entered field " +  user_iterator1.toString()+ " exists in Source ");
              }


              else if(!Src_iterator2.hasNext() || !user_iterator1.next().equals(Src_iterator2.next())){

                  System.out.println("User Entered field " +   user_iterator1.toString() + " is not correct ");

              }
            }
John Humphreys - w00te :

You can do a couple of things here.

First of all, you can change both lists into sets. Then you can use union and difference to get the matching elements and the differing elements in either direction.

public static void main(String[] args) {
    List<Integer> first = Arrays.asList(1, 3, 5, 7, 9);
    List<Integer> second = Arrays.asList(1, 5, 12);

    Set<Integer> first_set = new HashSet<>(first);
    Set<Integer> second_set = new HashSet<>(second);

    System.out.println(Sets.difference(first_set, second_set));
    System.out.println(Sets.difference(second_set, first_set));
    System.out.println(Sets.intersection(first_set, second_set));
    System.out.println(Sets.union(first_set, second_set));
}

Output

[3, 7, 9]
[12]
[1, 5]
[1, 3, 5, 7, 9, 12]

Second, you can sort the lists first, and progress through them both, only advancing the lower (value) iterator so you can detect matches. Stop when you reach the end of one and the rest is part of the difference from the second.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=329298&siteId=1