Java compare list elements

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] 

Источник

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.

Читайте также:  Light green color css

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

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

Читайте также:  Html шаблоны one page

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));

Источник

Interface List

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2) , and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator , add , remove , equals , and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator , that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

Читайте также:  Javascript access local files

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

Unmodifiable Lists

  • They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the List’s contents to appear to change.
  • They disallow null elements. Attempts to create them with null elements result in NullPointerException .
  • They are serializable if all elements are serializable.
  • The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
  • The lists and their subList views implement the RandomAccess interface.
  • They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
  • They are serialized as specified on the Serialized Form page.

This interface is a member of the Java Collections Framework.

Источник

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