Как сравнить две коллекции java

от admin

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

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.

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.

2.1. Plain Java

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.

2.2. Using Stream API

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.

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.

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:

The solution using the stream API is as follows:

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

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.

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

Проверьте, равны ли два списка в Java

Списки на Java упорядочены по природе. Таким образом, два списка считаются равными, если они содержат одинаковые элементы в одинаковом порядке. В этом уроке мы увидим, как сравнить два списка на равенство в Java.

Мы также рассмотрим способы сравнения элементов в двух списках и игнорирования их порядка.

Порядок поддержания равенства списков:

Как мы знаем, два списка равны, когда они имеют одинаковые элементы и в одинаковом порядке. Поэтому, если мы заботимся о порядке, мы можем использовать метод equals () для проверки равенства:

И list1, и list3 содержат одинаковые элементы <1, 2, 3>, но в разных порядках и поэтому считаются неравными.

Порядок игнорирования равенства списков:

Что если мы хотим игнорировать порядок элементов для проверки на равенство?

Много раз все, что мы хотим, это проверить, содержат ли два списка одинаковые элементы, независимо от их порядка в списке. Давайте рассмотрим способы достижения этого:

1. Сортировка списков и сравнение:

Если оба списка нулевые , мы вернем true . Или же, если только один из них указывает на нулевое значение или размер () двух списков отличается, мы вернем false . Если ни одно из этих условий не выполняется, мы сначала отсортируем два списка, а затем сравним их:

Обратите внимание, что мы создали копии двух списков, чтобы гарантировать, что элементы в исходных списках остаются нетронутыми .

2. С помощью Set / содержит () Проверьте:

Если данные в наших списках уникальны, т.е. нет дублирования, мы можем просто создать TreeSets из заданных списков и затем сравнить их с помощью equals () :

Мы можем еще больше упростить это, просто установив проверку на проверку содержимого () вместо создания наборов :

Однако обратите внимание, что эти подходы ( contains () check / With Sets ) потерпят неудачу, если в нашем наборе данных есть повторы. Например:

В приведенном выше примере l ist1 содержит одно 2 и два 3, а list2 содержит два 2 и одно 3 . Тем не менее, эта форма реализации будет неверно возвращать true .

3. Apache Commons:

Вместо написания собственного кода мы можем выбрать для выполнения утилиту Apache Commons Collections :

Метод isEqualCollection () возвращает true, если две коллекции содержат абсолютно одинаковые элементы с одинаковым количеством элементов.

Вывод:

В этом уроке мы научились проверять, равны ли два списка в Java. Теперь мы знаем, что по умолчанию два списка равны, если они имеют одинаковые элементы в одинаковом порядке.

Мы также обсудили подходы, которые мы можем использовать для проверки равенства списков, если мы не заботимся о порядке элементов.

Оставьте первый комментарий.

Опубликовано на Java Code Geeks с разрешения Шубхры Шриваставы, партнера нашей программы JCG . Смотрите оригинальную статью здесь: Проверьте, равны ли два списка в Java

Мнения, высказанные участниками Java Code Geeks, являются их собственными.

How Best to Compare Two Collections in Java and Act on Them?

I have two collections of the same object, Collection<Foo> oldSet and Collection<Foo> newSet . The required logic is as follow:

  • if foo is in(*) oldSet but not newSet , call doRemove(foo)
  • else if foo is not in oldSet but in newSet , call doAdd(foo)
  • else if foo is in both collections but modified, call doUpdate(oldFoo, newFoo)
  • else if !foo.activated && foo.startDate >= now , call doStart(foo)
  • else if foo.activated && foo.endDate <= now , call doEnd(foo)

(*) «in» means the unique identifier matches, not necessarily the content.

The current (legacy) code does many comparisons to figure out removeSet , addSet , updateSet , startSet and endSet , and then loop to act on each item.

The code is quite messy (partly because I have left out some spaghetti logic already) and I am trying to refactor it. Some more background info:

  • As far as I know, the oldSet and newSet are actually backed by ArrayList
  • Each set contains less than 100 items, most likely max out at 20
  • This code is called frequently (measured in millions/day), although the sets seldom differ
  • If I convert oldSet and newSet into HashMap<Foo> (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time & memory performance is loss on the conversion?
  • Would iterating the two sets and perform the appropriate operation be more efficient and concise?

8 Answers 8

Apache’s commons.collections library has a CollectionUtils class that provides easy-to-use methods for Collection manipulation/checking, such as intersection, difference, and union.

The org.apache.commons.collections.CollectionUtils API docs are here.

You can use Java 8 streams, for example

I have created an approximation of what I think you are looking for just using the Collections Framework in Java. Frankly, I think it is probably overkill as @Mike Deck points out. For such a small set of items to compare and process I think arrays would be a better choice from a procedural standpoint but here is my pseudo-coded (because I’m lazy) solution. I have an assumption that the Foo class is comparable based on it’s unique id and not all of the data in it’s contents:

As far as your questions: If I convert oldSet and newSet into HashMap (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time & memory performance is loss on the conversion? I think that you would probably make the code more readable by using a Map BUT. you would probably use more memory and time during the conversion.

Would iterating the two sets and perform the appropriate operation be more efficient and concise? Yes, this would be the best of both worlds especially if you followed @Mike Sharek ‘s advice of Rolling your own List with the specialized methods or following something like the Visitor Design pattern to run through your collection and process each item.

Java Compare Two Lists

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:

As you can see the equals() method compares the items and their location in the list.

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.

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:

Likewise, if we used:

Compare two lists, find common items

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

Читать:
File stdin line 1 что за ошибка

Похожие статьи