Programming Student
Programming Student

Reputation: 57

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 it will return true, otherwise false.

Upvotes: 4

Views: 24972

Answers (4)

cybye
cybye

Reputation: 1171

Have 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 the order does not matter

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

Upvotes: 14

Jayamohan
Jayamohan

Reputation: 12924

You can try using Apache commons CollectionUtils.retainAll method : Returns a collection containing all the elements 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 both the list are same.

Upvotes: 3

Manish Prajapati
Manish Prajapati

Reputation: 392

The following code is used. This checks whether two list have same element or not. -->> list1.equals(list2)

Upvotes: 0

viq
viq

Reputation: 417

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 don't use foreach statement because i had read this post http://habrahabr.ru/post/164177/ (on russian), but you can translate it to english.

Upvotes: 0

Related Questions