Compare two collections java

How to Compare Two Lists in Java

Learn to compare two ArrayList in Java to find if they contain equal elements. If both lists are unequal, we will find the difference between the lists. We will also learn to find common as well as different items in each list.

Note that the difference between two lists is equal to a third list which contains either additional elements or missing elements.

1. Comparing Two ArrayList for Equality

The following Java program tests if two given lists are equal. To test equality, we need to sort both lists and compare both lists using equals() method.

The List.equals() method returns true for two list instances if and only if:

  • both lists are of the same size
  • both contain the same elements in exactly the same order
ArrayList list = new ArrayList<>(Arrays.asList("a", "b", "c")); ArrayList equalList = new ArrayList<>(Arrays.asList("c", "b", "a")); ArrayList diffList = new ArrayList<>(Arrays.asList("a", "b", "d")); //c and d are changed Collections.sort(list); Collections.sort(equalList); Assertions.assertTrue(list.equals(equalList)); Collections.sort(diffList); Assertions.assertFalse(list.equals(diffList));

If you have commons-collections4 dependency in the project, we can use the CollectionUtils.isEqualCollection() API. This API compares the items from both lists, ignoring the order.

Assertions.assertTrue(CollectionUtils.isEqualCollection(list, equalList));

If we are checking the list equality in unit tests, then consider using the Matchers.containsInAnyOrder().

2. List Difference – Find Additional Items

Читайте также:  Python print all files in directory

In the following examples, we will find the items that are present in list1, but not in list2.

If two arraylists are not equal and we want to find what additional elements are in the first list compared to the second list, use the removeAll() method. It removes all elements of the second list from the first list and leaves only additional elements in the first list.

ArrayList listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d")); ArrayList listTwo = new ArrayList<>(Arrays.asList("a", "b", "e", "f")); //additional items in listOne listOne.removeAll(listTwo); System.out.println(listOne); //[c, d]

We can iterate over the List items of the first list, and search all elements in the second list. If the element is present in the second list, remove it from the first list. After the stream operations, collect the items to a new list.

List listOfAdditionalItems = listOne.stream() .filter(item -> !listTwo.contains(item)) .toList(); Assertions.assertTrue(CollectionUtils.isEqualCollection(List.of("c", "d"), listOfAdditionalItems));

2.3. Using CollectionUtils.removeAll()

The CollectionUtils.removeAll(list1, list2) returns a collection containing all the elements in list1 that are not in list2. The CollectionUtils class is part of Apache commons-collection4 library.

List listOfAdditionalItems = (List) CollectionUtils.removeAll(listOne, listTwo); Assertions.assertTrue(CollectionUtils.isEqualCollection(List.of("c", "d"), listOfAdditionalItems));

3. Map Difference – Find Missing Items

To get the missing elements in list 1, which are present in list 2, we can reverse the solutions in the previous section.

The Solution using plain Java is:

ArrayList listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d")); ArrayList listTwo = new ArrayList<>(Arrays.asList("a", "b", "e", "f")); //missing items in listOne listTwo.removeAll(listOne); System.out.println(listTwo); //[e, f]

The solution using the stream API is as follows:

List listOfMissingItems = listTwo.stream() .filter(item -> !listOne.contains(item)) .toList(); Assertions.assertTrue(CollectionUtils.isEqualCollection(List.of("e", "f"), listOfMissingItems));

Similarly, use the CollectionUtils.removeAll() with the list ordered reversed.

List listOfMissingItems = (List) CollectionUtils.removeAll(listTwo, listOne); Assertions.assertTrue(CollectionUtils.isEqualCollection(List.of("e", "f"), listOfMissingItems));

4. Map Difference – Find Common Items

To find common elements in two arraylists, use List.retainAll() method. This method retains only the elements in this list that are contained in the specified arraylist passed as method argument.

ArrayList listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d")); ArrayList listTwo = new ArrayList<>(Arrays.asList("a", "b", "e", "f")); //common items in listOne and listTwo listOne.retainAll(listTwo); //[a, b]

We can use the Stream API to find all the common items as follows:

List listOfCommonItems = listOne.stream() .filter(item -> listTwo.contains(item)) .toList(); Assertions.assertTrue(CollectionUtils.isEqualCollection(List.of("a", "b"), listOfCommonItems));

Also, the CollectionUtils.intersection() method can be used that returns the common elements in two lists.

List listOfCommonItems = (List) CollectionUtils.intersection(listTwo, listOne); Assertions.assertTrue(CollectionUtils.isEqualCollection(List.of("a", "b"), listOfCommonItems));

Источник

Comparing Two Lists In Java

This article demonstrates ways of comparing two Java Lists to find the common elements or missing elements.

Overview

We often use Java Lists as a general-purpose collection of ordered elements. We often need to compare two Java Lists for equality or to find their common or differentiating elements. Consider we have two Lists of Student instances, one that contains Math toppers and the other contains Sports toppers. We may want to compare the two Lists to find the Students who equally perform well in Sports and Maths or the Sports toppers which are poor in Maths.

There is no direct way to compare Java Lists to find their commonality or particularity in Java. However, there are a couple of workarounds that we are going to learn in the following sections.

Comparing Two Lists for Equality

We can use the equals() method from the List interface to compare two Java Lists for equality. As per the documentation, the equals() method returns true if:

Example of comparing Java Lists for equality

List one = List.of(1, 2, 4, 6, 8); List two = List.of(1, 2, 4, 6, 8); List three = List.of(1, 2, 4, 6, 8, 4); System.out.println(one.equals(two)); System.out.println(one.equals(three)); //prints: //true //falseCode language: Java (java)

Our article demonstrates how to assert using popular Unit Testing Frameworks if two java Lists are equal.

Common Elements in Two Lists

There are a few ways to find common elements between two Java Lists. Consider we have the following two List instances.

List one = List.of(1, 2, 4, 6, 8); List two = List.of(3, 4, 5, 6, 7);Code language: Java (java)

Plain Java

The retainAll() method of Java List removes all elements from this List except those from the given List. We can use it to find the elements common to two ArrayLists.

Example of finding common elements between two Lists using plain Java.

List commons = new ArrayList<>(one); commons.retainAll(two); System.out.println(commons); //prints: //[4, 6]Code language: Java (java)

The retainAll() method modifies this List. Hence we have made a copy of the List to keep it unchanged.

Java Streams

Alternatively, we can use Java Streams API to find common elements between two Lists. To do that, we can create a Stream of the first List and use the filter() method to retain only the elements in the second List.

Example of using Java Streams to find common elements between two Java Lists.

List commons = one.stream() .filter(two::contains) .toList(); System.out.println(commons); //prints: //[4, 6]Code language: Java (java)

Apache Commons Collections

The CollectionUtils class in the Commons Collections library provides many useful abstractions, including the intersection() method. The method takes two Java Collections and returns a Collection instance containing their common elements.

Example of finding common elements of two Lists using Commons Collections.

List commons = new ArrayList<>( CollectionUtils.intersection(one, two)); System.out.println(commons); //prints: //[4, 6]Code language: Java (java)

Difference between Two Lists

So far, we have been interested in finding the elements present in both Lists. Now let’s understand how to find the difference between two ArrayLists in Java.

Example of finding the difference between two Java Lists.

List difference = new ArrayList<>(one); difference.removeAll(two); System.out.println(difference); //prints: //[1, 2, 8]Code language: Java (java)

Here, we are using the removeAll() method to find the elements of the first List that do not exist in the second. To keep the original List unchanged, we copied it before using the removeAll() method.

Please read our detailed article to learn how to find the difference between two Java Lists.

Summary

This quick tutorial described different ways of comparing two Java List instances. We compared two Java Lists for equality, listed their common elements, and identified their differences.

Please refer to our GitHub Repository for the complete source code.

Источник

Java Compare Two Lists

Last updated: 17 March 2020 The List interface in Java provides methods to be able to compare two Lists and find the common and missing items from the lists.

Compare two unsorted lists for equality

If you want to check that two lists are equal, i.e. contain the same items and and appear in the same index then we can use:

import java.util.Arrays; import java.util.List; public class CompareTwoLists < public static void main(String[] args) < ListlistOne = Arrays.asList("a", "b", "c"); List listTwo = Arrays.asList("a", "b", "c"); List listThree = Arrays.asList("c", "a", "b"); boolean isEqual = listOne.equals(listTwo); System.out.println(isEqual); isEqual = listOne.equals(listThree); System.out.println(isEqual); > > 

Compare two sorted lists

Do two lists contain same items?

To compare two lists for equality just in terms of items regardless of their location, we need to use the sort() method from the Collections() class.

import java.util.Arrays; import java.util.Collections; import java.util.List; public class CompareTwoLists < public static void main(String[] args) < ListlistOne = Arrays.asList("b", "c", "a"); List listTwo = Arrays.asList("a", "c", "b"); List listThree = Arrays.asList("c", "a", "b"); Collections.sort(listOne); Collections.sort(listTwo); Collections.sort(listThree); boolean isEqual = listOne.equals(listTwo); System.out.println(isEqual); isEqual = listOne.equals(listThree); System.out.println(isEqual); > > 

Compare two lists, find differences

The List interface also provides methods to find differences between two lists.

The removeAll() method compares two lists and removes all the common items. What’s left is the additional or missing items.

For example when we compare two lists, listOne and listTwo and we want to find out what items are missing from listTwo we use:

import java.util.ArrayList; import java.util.Arrays; public class CompareTwoArrayLists < public static void main(String[] args) < ArrayListlistOne = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); ArrayList listTwo = new ArrayList<>(Arrays.asList(1, 2, 4, 5, 6, 7)); listOne.removeAll(listTwo); System.out.println("Missing items from listTwo " + listOne); > > 
Missing items from listTwo [3] 
listTwo.removeAll(listOne); System.out.println("Missing items from listOne " + listTwo); 
Missing items from listOne [6, 7] 

Compare two lists, find common items

The retainAll() method only keeps the items that are common in both lists. For example:

public class CompareTwoArrayLists < public static void main(String[] args) < ArrayListlistOne = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); ArrayList listTwo = new ArrayList<>(Arrays.asList(1, 2, 4, 5, 6, 7)); listOne.retainAll(listTwo); System.out.println("Common items in both lists " + listOne); > > 
Common items in both lists [1, 2, 4, 5] 

Источник

Оцените статью