Como comparar duas listas java

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) { List<String> listOne = Arrays.asList("a", "b", "c"); List<String> listTwo = Arrays.asList("a", "b", "c"); List<String> listThree = Arrays.asList("c", "a", "b"); boolean isEqual = listOne.equals(listTwo); System.out.println(isEqual); isEqual = listOne.equals(listThree); System.out.println(isEqual); } }

Output:

true false

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

Related:

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.

For example:

import java.util.Arrays; import java.util.Collections; import java.util.List; public class CompareTwoLists { public static void main(String[] args) { List<String> listOne = Arrays.asList("b", "c", "a"); List<String> listTwo = Arrays.asList("a", "c", "b"); List<String> 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); } }

Output:

true true

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) { ArrayList<Integer> listOne = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); ArrayList<Integer> listTwo = new ArrayList<>(Arrays.asList(1, 2, 4, 5, 6, 7)); listOne.removeAll(listTwo); System.out.println("Missing items from listTwo " + listOne); } }

Output:

Missing items from listTwo [3]

Likewise, if we used:

listTwo.removeAll(listOne); System.out.println("Missing items from listOne " + listTwo);

We would get:

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) { ArrayList<Integer> listOne = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); ArrayList<Integer> listTwo = new ArrayList<>(Arrays.asList(1, 2, 4, 5, 6, 7)); listOne.retainAll(listTwo); System.out.println("Common items in both lists " + listOne); } }

Output:

Common items in both lists [1, 2, 4, 5]

Este post discutirá como comparar duas listas para igualdade em Java, ignorando a ordem. A Lista pode ser uma Lista de tipos primitivos ou uma Lista de Objetos. Duas listas são definidas como iguais se contiverem exatamente os mesmos elementos em igual quantidade cada, em qualquer ordem.

Por exemplo, [1, 2, 3] e [2, 1, 3] são considerados iguais, enquanto [1, 2, 3] e [2, 4, 3] não são. A contagem dos elementos também importa, portanto, [1, 2, 3, 1] e [2, 1, 3, 2] não são tratados igualmente. Se a contagem de elementos não importa, você pode converter ambas as listas em um conjunto e compará-las usando o .equals() método da interface Set.

1. Classificação

Uma solução simples é ordenar ambas as listas e, em seguida, compará-los usando o .equals() método do List interface. Observe que esta solução não é linear e tem O(n.log(n)) complexidade do tempo. Não é adequado para grandes listas.

Para melhorar a eficiência, é recomendável verificar primeiro se ambas as listas têm o mesmo tamanho ou não. Além disso, antes de classificar as duas listas, crie sua cópia para evitar destruir a ordem original de ambas as listas. As etapas de cópia e classificação podem ser feitas com eficiência usando a API do Streams, conforme mostrado abaixo.

import java.util.stream.Collectors;

    public static boolean isEqualIgnoringOrder(List<Integer> x, List<Integer> 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<Integer> x = List.of(1, 2, 3);

        List<Integer> 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  Executar código

Resultado:
Both lists are equal

2. Usando Multiconjunto

Outra solução é converter ambas as listas para multiset e comparar o multiset, que compara os elementos independentemente de sua ordem e também preserva a contagem de elementos duplicados. A solução a seguir demonstra isso usando Multiconjunto de goiaba.

import com.google.common.collect.ImmutableMultiset;

    public static boolean isEqualIgnoringOrder(List<Integer> x, List<Integer> y) {

        if (x.size() != y.size()) {

        return ImmutableMultiset.copyOf(x).equals(ImmutableMultiset.copyOf(y));

    public static void main(String[] args)

        List<Integer> x = List.of(1, 2, 2);

        List<Integer> 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");

Código de download

Resultado:
Both lists are not equal

3. Biblioteca Apache Commons Lang

Finalmente, a Apache Commons Lang Library oferece a CollectionUtils.isEqualCollection() método, que retorna true se as coleções fornecidas contiverem exatamente os mesmos elementos com exatamente as mesmas cardinalidades.

import org.apache.commons.collections4.CollectionUtils;

    public static void main(String[] args)

        List<Integer> x = List.of(1, 2, 3);

        List<Integer> 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");

Código de download

Resultado:
Both lists are equal

4. Verifique a igualdade na Lista de objetos

Para comparar duas listas de objetos usando qualquer um dos métodos acima, você precisa substituir métodos equals e hashCode para esse objeto em Java. O programa a seguir demonstra isso:

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<President> x = List.of(

                new President("Trump", 75),

                new President("Obama", 60),

                new President("Trump", 75));

        List<President> 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");

Código de download

Resultado:
Both lists are equal

Isso é tudo sobre comparar duas listas para igualdade em Java, ignorando a ordem.


Obrigado por ler.

Por favor, use nosso compilador online para postar código em comentários usando C, C++, Java, Python, JavaScript, C#, PHP e muitas outras linguagens de programação populares.

Como nós? Indique-nos aos seus amigos e ajude-nos a crescer. Codificação feliz 🙂


Última postagem

Tag