[英]How to compare two ArrayList<List<String>>
我想比較這兩個ArrayList
:
public static ArrayList<List<String>> arrayList1 = new ArrayList<List<String>>();
public static ArrayList<List<String>> arrayList2 = new ArrayList<List<String>>();
如果它們具有相同的元素,則返回true,否則為false。
你有沒有嘗試過
arrayList1 .equals ( arrayList2 )
如果它們包含相同順序的相同元素,則為true
要么
new HashSet(arrayList1) .equals (new HashSet(arrayList2))
如果訂單無關緊要
請參見http://www.docjar.com/html/api/java/util/AbstractList.java.html
您可以嘗試使用Apache commons CollectionUtils.retainAll方法:返回一個集合,其中包含collection1中也在collection2中的所有元素。
ArrayList commonList = CollectionUtils.retainAll(arrayList1, arrayList2);
如果arrayList1
的大小等於arrayList1
和arrayList2
,則可以說列表都相同。
我認為你可以自己做,沒有任何依賴。
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;
}
}
並使用
ListComparator<String> compare = new ListComparator<String>();
System.out.println(compare.compare(arrayList1, arrayList2));
我不使用foreach聲明,因為我已經閱讀了這篇文章http://habrahabr.ru/post/164177/ (俄語),但你可以將它翻譯成英語。
使用以下代碼。 這將檢查兩個列表是否具有相同的元素。 - >> list1.equals(list2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.