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
falseThe 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:
trueAs 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:
trueCommon 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
trueFunctions 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.