Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if all elements of list are in a set in Java 8?

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 ?

like image 261
Tanvi Jaywant Avatar asked May 18 '18 18:05

Tanvi Jaywant


People also ask

How do you check if an element is present in a list in Java 8?

We can check whether an element exists in ArrayList in java in two ways: Using contains() method. Using indexOf() method.

How do you check if all elements in a Set are the same Java?

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.

How do you check if an item is in a Set Java?

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.

How do you find does ArrayList contains all list elements or not?

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);


2 Answers

You can use allMatch:

boolean result = l.stream().allMatch(s::contains);
like image 165
Ousmane D. Avatar answered Oct 12 '22 21:10

Ousmane D.


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
like image 37
Jacob G. Avatar answered Oct 12 '22 21:10

Jacob G.