While it is easy to do it in a for loop, is there a way in Java-8 to find if all elements in list L
are present in Set s
?
We can check whether an element exists in ArrayList in java in two ways: Using contains() method. Using indexOf() method.
The containsAll() method of Java Set is used to check whether two sets contain the same elements or not. It takes one set as a parameter and returns True if all of the elements of this set is present in the other set.
util. Set. contains() method is used to check whether a specific element is present in the Set or not. So basically it is used to check if a Set contains any particular element.
The Java ArrayList containsAll() method checks whether the arraylist contains all the elements of the specified collection. The syntax of the containsAll() method is: arraylist. containsAll(Collection c);
You can use allMatch
:
boolean result = l.stream().allMatch(s::contains);
There's no need to use a Stream
for this when you can use Set#containsAll
:
var set = Set.of(1, 2, 3, 4, 5);
var list = List.of(2, 3, 4);
System.out.println(set.containsAll(list));
Output:
true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With