How to compare two ArrayList <List <String>>

I want to compare these two ArrayList :

 public static ArrayList<List<String>> arrayList1 = new ArrayList<List<String>>(); public static ArrayList<List<String>> arrayList2 = new ArrayList<List<String>>(); 

If they have the same elements, they will return true, otherwise false.

+4
source share
4 answers

You can try using the public resources of Apache CollectionUtils.retainAll : returns a collection containing all the items in collection1 that are also in collection2.

 ArrayList commonList = CollectionUtils.retainAll(arrayList1, arrayList2); 

If the size of commonList is equal to arrayList1 and arrayList2 , you can say that both lists are the same.

+3
source

You tried

  arrayList1 .equals ( arrayList2 ) 

which is true if they contain the same elements in the same order

or

 new HashSet(arrayList1) . equals (new HashSet(arrayList2)) 

if order doesn't matter

See http://www.docjar.com/html/api/java/util/AbstractList.java.html

+13
source

I think you can do it yourself without any dependencies.

 public class ListComparator<T> { public Boolean compare(List<List<T>> a, List<List<T>> b) { if (a.size() != b.size()) { return false; } for (int i = 0; i < a.size(); i++) { if (a.get(i).size() != b.get(i).size()) { return false; } for (int k = 0; k < a.get(i).size(); k++) { if(!a.get(i).get(k).equals(b.get(i).get(k))) { return false; } } } return true; } } 

And using

  ListComparator<String> compare = new ListComparator<String>(); System.out.println(compare.compare(arrayList1, arrayList2)); 

I do not use the foreach operator because I read this post http://habrahabr.ru/post/164177/ (in Russian), but you can translate it into English.

0
source

The following code is used. This checks if the two lists have the same item or not. - β†’ list1.equals (list2)

0
source

All Articles