How to compare two ArrayList>

2020-02-10 09:12发布

问题:

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.

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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