Contents
Bạn đang tìm kiếm từ khóa Compare two list Java được Update vào lúc : 2022-03-10 05:43:18 . Với phương châm chia sẻ Thủ Thuật về trong nội dung bài viết một cách Chi Tiết 2022. Nếu sau khi đọc tài liệu vẫn ko hiểu thì hoàn toàn có thể lại phản hồi ở cuối bài để Mình lý giải và hướng dẫn lại nha.
Nội dung chính
In this tutorial, we are going to see how to compare two ArrayList in Java. You can compare two ArrayLists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it to the current object, if there is a match, it returns TRUE and otherwise, it returns FALSE.
Java Program to Compare Two ArrayList:
import java.util.ArrayList;
public class Main
public static void main(String[] args)
ArrayList list1 = new ArrayList();
list1.add(“Java”);
list1.add(“PHP”);
list1.add(“Python”);
list1.add(“Pascal”);
ArrayList list2 = new ArrayList();
list2.add(“Java”);
list2.add(“PHP”);
list2.add(“Python”);
list2.add(“Pascal”);
if(list1.equals(list2))
System.out.println(“The two ArrayList are equal.”);
else
System.out.println(“The two ArrayList are not equal.”);
Output:
The two arraylists are equal.
[wbcr_php_snippet id=”598″ title=”GetPreviousPost” postid= “1796”]
[wbcr_php_snippet id=”125″ title=”GetPreviousPost” category_id= “9”]
Comparing two ArrayLists could be a tricky task for beginner programmers. On this page, we are going to share some of the best ways to compare two ArrayLists.
You can easily compare the two ArrayLists by simply using the equals() method. This method returns a boolean value(True or False). So, if the result is true, the ArrayLists are equal; otherwise, they are not equal.
import java.util.ArrayList;
public class ComparingArrayLists //using equals()
public static void main(String[] args)
//initializing two array lists
ArrayList list1 = new ArrayList ();
ArrayList list2 = new ArrayList ();
//storing data in list 1
list1.add(“Java”);
list1.add(“Python”);
list1.add(“C++”);
//storing data in list 2
list2.add(“Java”);
list2.add(“Python”);
list2.add(“C++”);
//printing both lists
System.out.println(“List 1:” + list1);
System.out.println(“List 2:” + list2);
//comparing both lists
if (list1.equals(list2))
System.out.println(“Lists are equal”);
else
System.out.println(“Lists are not equal”);
//adding another element to list 1
list1.add(“HTML”);
//comparing both lists again
if (list1.equals(list2))
System.out.println(“Lists are equal”);
else
System.out.println(“Lists are not equal”);
run:
List 1:[Java, Python, C++]
List 2:[Java, Python, C++]
Lists are equal
Lists are not equal
BUILD SUCCESSFUL (total time: 5 seconds)
In case you want to compare two ArrayLists with respect to common elements, then you should be trying retainAll() method. It will return all common elements between two ArrayLists.
import java.util.ArrayList;
public class ComparingArrayLists //using retainAll()
public static void main(String[] args)
//initializing two array lists
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
//storing data in list 1
list1.add(“Mike”);
list1.add(“Sara”);
list1.add(“John”);
//storing data in list 2
list2.add(“Mike”);
list2.add(“Sara”);
list2.add(“Diaz”);
list2.add(“Sam”);
//printing both lists
System.out.println(“List 1:” + list1);
System.out.println(“List 2:” + list2);
//it will return common elements
list2.retainAll(list1);
//printing common elements
System.out.println(“Common elements are: ” + list2);
run:
List 1:[Mike, Sara, John]
List 2:[Mike, Sara, Diaz, Sam]
Common elements are: [Mike, Sara]
BUILD SUCCESSFUL (total time: 14 seconds)
An alternate way of retainAll() is to compare the elements of the ArrayLists using contains() method. The contains() method checks whether List 1 has the same element as List 2 the same index.
import java.util.ArrayList;
import java.util.Arrays;
public class ComparingArrayLists //using contains()
public static void main(String[] args)
//initializing two array lists
ArrayList list1 = new ArrayList(Arrays.asList(“Apple”, “Banana”, “Peach”, “Apricot”));
ArrayList list2 = new ArrayList(Arrays.asList(“Cabbage”, “Carrots”, “Cucumber”, “Banana”));
//printing both lists
System.out.println(“List 1:” + list1);
System.out.println(“List 2:” + list2);
//Finding similar items in both lists
int i=0;
while(i<list1.size() && i<list2.size())
if(list2.contains(list1.get(i)))
System.out.println(list1.get(i) + " is in both lists");
i++;
run:
List 1:[Apple, Banana, Peach, Apricot]
List 2:[Cabbage, Carrots, Cucumber, Banana]
Banana is in both lists
BUILD SUCCESSFUL (total time: 7 seconds)
Happy Learning ?
This post will discuss how to compare two lists for equality in Java, ignoring the order. The List may be a List of primitive types or a List of Objects. Two lists are defined to be equal if they contain exactly the same elements in equal quantity each, in any order.
For example, [1, 2, 3] and [2, 1, 3] are considered equal, while [1, 2, 3] and [2, 4, 3] are not. The elements’ count also matters, hence, [1, 2, 3, 1] and [2, 1, 3, 2] are not treated equally. If the elements count doesn’t matter, you can convert both lists to a Set and compare them using the .equals() method of the Set interface.
A simple solution is to sort both lists and then compare them using the .equals() method of the List interface. Note that this solution is not linear, and has O(n.log(n)) time complexity. It is not suitable for large lists.
To improve efficiency, it is recommended to first check if both lists have the same size or not. Also before sorting both lists, create their copy to avoid destroying the original order of both lists. Both copying and sorting steps can be done efficiently using Streams API, as shown below.
import java.util.stream.Collectors;
public static boolean isEqualIgnoringOrder(List x, List y) {
if (x.size() != y.size()) {
x = x.stream().sorted().collect(Collectors.toList());
y = y.stream().sorted().collect(Collectors.toList());
public static void main(String[] args)
List x = List.of(1, 2, 3);
List y = List.of(2, 3, 1);
boolean isEqual = isEqualIgnoringOrder(x, y);
System.out.println(“Both lists are equal”);
System.out.println(“Both lists are not equal”);
Download Run Code
Output:
Both lists are equal
Another solution is to convert both lists to multiset and compare the multiset, which compares elements regardless of their order and also preserves the count of duplicate elements. The following solution demonstrates this using Guava’s Multiset.
import com.google.common.collect.ImmutableMultiset;
public static boolean isEqualIgnoringOrder(List x, List y) {
if (x.size() != y.size()) {
return ImmutableMultiset.copyOf(x).equals(ImmutableMultiset.copyOf(y));
public static void main(String[] args)
List x = List.of(1, 2, 2);
List y = List.of(1, 2, 1);
boolean isEqual = isEqualIgnoringOrder(x, y);
System.out.println(“Both lists are equal”);
System.out.println(“Both lists are not equal”);
Download Code
Output:
Both lists are not equal
Finally, Apache Commons Lang Library offers the CollectionUtils.isEqualCollection() method, which returns true if the given Collections contain exactly the same elements with exactly the same cardinalities.
import org.apache.commons.collections4.CollectionUtils;
public static void main(String[] args)
List x = List.of(1, 2, 3);
List y = List.of(2, 3, 1);
boolean isEqual = CollectionUtils.isEqualCollection(x, y);
System.out.println(“Both lists are equal”);
System.out.println(“Both lists are not equal”);
Download Code
Output:
Both lists are equal
To compare two lists of objects using any of the above methods, you need to override equals and hashCode methods for that object in Java. The following program demonstrates it:
import org.apache.commons.collections4.CollectionUtils;
President(String name, int age) {
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
President person = (President) o;
return age == person.age && Objects.equals(name, person.name);
return Objects.hash(name, age);
public static void main(String[] args)
List x = List.of(
new President(“Trump”, 75),
new President(“Obama”, 60),
new President(“Trump”, 75));
List y = List.of(
new President(“Obama”, 60),
new President(“Trump”, 75),
new President(“Trump”, 75));
boolean isEqual = CollectionUtils.isEqualCollection(x, y);
System.out.println(“Both lists are equal”);
System.out.println(“Both lists are not equal”);
Download Code
Output:
Both lists are equal
That’s all about comparing two lists for equality in Java, ignoring the order.
Thanks for reading.
Please use our trực tuyến compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and help us grow. Happy coding ?
://.youtube/watch?v=e833X3i4H2o
Bạn vừa tìm hiểu thêm tài liệu Với Một số hướng dẫn một cách rõ ràng hơn về Review Compare two list Java tiên tiến và phát triển nhất
Hero đang tìm một số trong những ShareLink Tải Compare two list Java miễn phí.
Nếu sau khi đọc nội dung bài viết Compare two list Java vẫn chưa hiểu thì hoàn toàn có thể lại Comment ở cuối bài để Tác giả lý giải và hướng dẫn lại nha
#Compare #list #Java
Tra Cứu Mã Số Thuế MST KHƯƠNG VĂN THUẤN Của Ai, Công Ty Doanh Nghiệp…
Các bạn cho mình hỏi với tự nhiên trong ĐT mình gần đây có Sim…
Thủ Thuật về Nhận định về nét trẻ trung trong môi trường tự nhiên vạn…
Thủ Thuật về dooshku là gì - Nghĩa của từ dooshku -Thủ Thuật Mới 2022…
Kinh Nghiệm Hướng dẫn Tìm 4 số hạng liên tục của một cấp số cộng…
Mẹo Hướng dẫn Em hãy cho biết thêm thêm nếu đèn huỳnh quang không còn…