How to compare two ArrayList<List<String>>

蹲街弑〆低调 提交于 2019-12-18 04:23:41

问题


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)



来源:https://stackoverflow.com/questions/14545303/how-to-compare-two-arraylistliststring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!