Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to compare two lists

Short answer

A list's equals() compares the elements in order:

void main() {
    var a = List.of(1, 2, 3);
    var b = new ArrayList<>(List.of(1, 2, 3));
    var c = List.of(3, 2, 1);
 
    IO.println(a.equals(b));
    IO.println(a.equals(c));
}

Output:

true
false

The list type does not matter: List.of() and an ArrayList with the same elements are equal.

Ignoring order

Sort copies and compare them:

void main() {
    var a = List.of("b", "a", "c");
    var b = List.of("c", "b", "a");
 
    IO.println(a.stream().sorted().toList().equals(b.stream().sorted().toList()));
}

Output:

true

As sets

If repeats do not matter, compare sets:

void main() {
    var a = List.of(1, 1, 2);
    var b = List.of(2, 1);
 
    IO.println(new HashSet<>(a).equals(new HashSet<>(b)));
}

Output:

true

Common mistake

Comparing lists with == or checking "sameness" with containsAll(). == compares references, and containsAll() ignores how many times elements repeat:

void main() {
    var a = List.of(1, 1, 1);
    var b = List.of(1, 2);
 
    IO.println(a == List.of(1, 1, 1));
    IO.println(b.containsAll(a));
}

Output:

false
true

Functions used in this recipe

  • Object.equals() — Compares objects by meaning. By default it works like ==, so classes override it.
  • HashSet — A set without duplicates backed by a hash table; order is not guaranteed.
  • List.contains() — Checks whether a list contains an element.

Thanks for reading!

Donate to the site — we work hard for you.