To check if a List contains all the elements of another List in Java, you can use the containsAll
method of the List interface.
In this example,
list1
and list2
containing integers.containsAll
method of list1
to check if it contains all elements of list2
.containsAll
method returns true
if all elements of list2
are present in list1
; otherwise, it returns false
.import java.util.List;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(2, 4);
boolean result = list1.containsAll(list2);
System.out.println("List 1 contains all elements of List 2: " + result);
}
}
List 1 contains all elements of List 2: true
In this example,
list1
and list2
containing strings.containsAll
method of list1
to check if it contains all elements of list2
.containsAll
method returns true
if all elements of list2
are present in list1
; otherwise, it returns false
.import java.util.List;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
List<String> list1 = Arrays.asList("apple", "banana", "orange", "kiwi");
List<String> list2 = Arrays.asList("banana", "kiwi");
boolean result = list1.containsAll(list2);
System.out.println("List 1 contains all elements of List 2: " + result);
}
}
List 1 contains all elements of List 2: true
In this tutorial, we learned How to check if a List contains all the elements of Another List in Java language with well detailed examples.