当前位置:网站首页>Compare whether two lists are equal
Compare whether two lists are equal
2022-07-05 00:50:00 【Sunze·】
1、 Use it directly equals() Compare
as everyone knows , When two lists have exactly the same elements and have exactly the same order , They are equal . therefore , If our business requires two list In the same order , have access to equals() Method to check the equality :
@Test
public void equalityCheckOfTwoLists() {
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(1, 2, 3);
List<Integer> list3 = Arrays.asList(2, 1, 3);
assertTrue(list1.equals(list2));
assertFalse(list1.equals(list3));
}
Even if list1 And projects list3 Contains the same elements {1,2,3}, But the order of elements is different , therefore list1 and list3 It's still not equal .
Be careful :
Some businesses require that the order of elements need not be consistent What we need to do is to check whether the two lists contain the same elements , Regardless of their order in the list , So how to achieve it ?
2、 take list Compare after sorting
Processing logic mainly includes :
(1) If two list All for null, Then return to true
(2) If one list Not empty , The other one points to null value and returns false
(3) Two list Of size() Different , return false.
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);
}
Please note that :
Here we create two copies of the list to ensure that the elements in the original list remain unchanged .
3、 Use Sets / contains() Compare list
If the list has no repeating elements , We can use list Created in TreeSet, And then use equals() Compare them :
ublic <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);
}
We can use it more simply contains() Compare , No need to create Sets:
return list1.containsAll(list2) && list2.containsAll(list1);
But pay attention here If we list Duplicate element , Use contains() perhaps Sets There will be problems in comparison . Look at the following case and you will know what happened .
List<Integer> list1 = Arrays.asList(1, 2, 3, 3);
List<Integer> list2 = Arrays.asList(3, 1, 2, 2);
// will return true, but actual value should be false
System.out.println(list1.isEquals(list2));
In the example above ,list1 Contains a 2 And two 3, and list2 Contains two 2 And a 3, We can see two list In fact, they are not equal , But the program will return incorrectly true. So when using this method, make sure list Elements are not repeated .
4、 Use Apache Commons Tool class
CollectionUtils It provides tools and methods for judging the equality of sets isEqualCollection, As long as we ensure that two sets are not empty, we can directly use this method to judge the equality of sets .
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
5、 Conclusion
Today we learned to check Java Whether the two lists in are equal 4 Methods , By default , When two lists have the same elements in the same order , We know they are equal . If we don't care much about the order of elements , Several other methods can be used to compare the equality of lists .
边栏推荐
- ORB(Oriented FAST and Rotated BRIEF)
- Specification for fs4061a boost 8.4v charging IC chip and fs4061b boost 12.6V charging IC chip datasheet
- Actual combat simulation │ JWT login authentication
- Date time type and format in MySQL
- Ruby tutorial
- POAP:NFT的采用入口?
- 华为200万年薪聘请数据治理专家!背后的千亿市场值得关注
- TS快速入门-函数
- 大专学历,33岁宝妈又怎样?我照样销售转测试,月入13k+
- Get to know ROS for the first time
猜你喜欢

揭露测试外包公司,关于外包,你或许听到过这样的声音

分布式BASE理论

2022.07.03 (LC 6108 decryption message)

初识ROS

URL和URI
![[paper reading] Tun det: a novel network for meridian ultra sound nodule detection](/img/25/e2366cabf00e55664d16455a6049e0.png)
[paper reading] Tun det: a novel network for meridian ultra sound nodule detection

Pycharm professional download and installation tutorial

lambda表达式
![Pandora IOT development board learning (RT thread) - Experiment 4 buzzer + motor experiment [key external interrupt] (learning notes)](/img/ad/5fbf8c3f71ea204bcd48473c3811f6.png)
Pandora IOT development board learning (RT thread) - Experiment 4 buzzer + motor experiment [key external interrupt] (learning notes)

小程序直播 + 电商,想做新零售电商就用它吧!
随机推荐
2022.07.03(LC_6109_知道秘密的人数)
What you learned in the eleventh week
URLs and URIs
Implementation steps of master detail detail layout mode of SAP ui5 application
P3304 [sdoi2013] diameter (diameter of tree)
Pandora IOT development board learning (RT thread) - Experiment 4 buzzer + motor experiment [key external interrupt] (learning notes)
Consolidated expression C case simple variable operation
Oracle case: SMON rollback exception causes instance crash
【selenium自动化】常用注解
P4408 [noi2003] truant children (tree diameter)
SAP UI5 应用的主-从-从(Master-Detail-Detail)布局模式的实现步骤
分布式BASE理论
PyTorch: In-place Operation
2022.07.03 (lc_6111_counts the number of ways to place houses)
What happened to those who focused on automated testing?
Huawei employs data management experts with an annual salary of 2million! The 100 billion market behind it deserves attention
Actual combat simulation │ JWT login authentication
[STM32] (I) overview and GPIO introduction
AcWing164. 可达性统计(拓扑排序+bitset)
6. Scala operator