In Java, to check if two lists have the same elements regardless of order, you can convert both lists to sets and compare them.
In this example,
list1
and list2
with the same set of elements.HashSet
class constructor.equals
method.import java.util.HashSet;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = List.of(1, 2, 3);
List<Integer> list2 = List.of(3, 2, 1);
boolean result = new HashSet<>(list1).equals(new HashSet<>(list2));
System.out.println("Do the lists have the same elements? " + result);
}
}
Do the lists have the same elements? true
In this example,
list1
and list2
with different sets of elements.HashSet
class constructor.equals
method.import java.util.HashSet;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = List.of(1, 2, 3);
List<Integer> list2 = List.of(4, 5, 6);
boolean result = new HashSet<>(list1).equals(new HashSet<>(list2));
System.out.println("Do the lists have the same elements? " + result);
}
}
Do the lists have the same elements? false
In this tutorial, we learned How to check if Two Lists have Same Elements (Regardless of Order) in Java language with well detailed examples.