10

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 ?

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
Tanvi Jaywant
  • 375
  • 1
  • 6
  • 18

3 Answers3

14

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
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • 1
    just becomes you can use `Set#containsAll` doesnt mean there is no need to use a stream... – Ousmane D. May 18 '18 at 21:09
  • @Aominè I argue that streaming it just adds overhead in this case. It's perfectly fine if other operations need to be performed first, such as filtering, mapping, etc. – Jacob G. May 18 '18 at 21:10
  • only worry about "overhead" when you notice a performance issue. – Ousmane D. May 18 '18 at 21:12
  • 8
    @Aominè: `set.containsAll(list)` is shorter and syntactically simpler than `l.stream().allMatch(s::contains)` and works reliably for twenty years now. So what's the reason to change when there isn’t even a performance advantage in using streams here? – Holger May 18 '18 at 21:28
  • @Holger that's not my point. the line "There's no need to use a Stream for this when you can use Set#containsAll" doesn't sit right with me. its like saying don't use `l.stream().filter(...).map(...)..` because you can do it with a `for` loop. – Ousmane D. May 18 '18 at 21:31
  • I just don't think the remote possibility of OP needing to map-reduce warrants the use of a `Stream` in this case. – Jacob G. May 18 '18 at 21:32
8

You can use allMatch:

boolean result = l.stream().allMatch(s::contains);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

Yes.

long commonElements = l.stream().filter(s::contains).count();
if (commonElements == l.size()) {
    //do something
}

Sets are nice because they are built for exactly this kind of thing: checking if an item exists already. Lists are not as good at this practice, but are good for quick traversal. So, you want to loop through the list and compare each element to the set, vs the other way around.

Streams are a nice resource for performing operations in-line vs explicitly breaking things out.

EDIT: @Aomine 's answer is better than mine

boolean result = myList.stream().allMatch(mySet::contains);
JRogerC
  • 598
  • 6
  • 17