0
点赞
收藏
分享

微信扫一扫

快速比较JAVA中两个集合是否相等


有几个方法:

1)如果是不在乎顺序,只要内容相同就可以认为相等,则:

public <T extends Comparable<T>> boolean isEquals(List<T> list1, List<T> list2){     
if (list1 == null && list2 == null) {
return true;
}
//Only one of them is null
else if(list1 == null || list2 == null) {
return false;
}
else if(list1.size() != list2.size()) {
return false;
}

//copying to avoid rearranging original lists
list1 = new ArrayList<T>(list1);
list2 = new ArrayList<T>(list2);

Collections.sort(list1);
Collections.sort(list2);

return list1.equals(list2);
}

如果LIST中没重复的元素,则可以:

public <T extends Comparable<T>> boolean isEquals(List<T> list1, List<T> list2){     
if (list1 == null && list2 == null) {
return true;
}
//Only one of them is null
else if(list1 == null || list2 == null) {
return false;
}
else if(list1.size() != list2.size()) {
return false;
}

Set<T> set1 = new TreeSet<>(list1);
Set<T> set2 = new TreeSet<>(list2);

return set1.equals(set2);
}

但注意如果有重复的话,使用上面的方法则不行,比如:
 

​​List<Integer> list1 = Arrays.asList(​​​​1​​​​, ​​​​2​​​​, ​​​​3​​​​, ​​​​3​​​​);​​
​​List<Integer> list2 = Arrays.asList(​​​​3​​​​, ​​​​1​​​​, ​​​​2​​​​, ​​​​2​​​​);​​
​​System.out.println(list1.isEquals(list2));​​
​​上面会认为是元素相同,个数相同,但实际上明显不是严格的相等了,最好是用apache common包:​​
​​List<Integer> list1 = Arrays.asList(​​​​1​​​​, ​​​​2​​​​, ​​​​3​​​​, ​​​​3​​​​);​​
​​List<Integer> list2 = Arrays.asList(​​​​3​​​​, ​​​​1​​​​, ​​​​3​​​​, ​​​​2​​​​);​​

​​System.out.println(CollectionUtils.isEqualCollection(list1, list2)); ​​​​//true​​

举报

相关推荐

0 条评论