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

3

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 ?

Addlebrained answered 18/5, 2018 at 18:47 Comment(1)
boolean result = s.equals(new HashSet(L));Obstinacy
M
8

You can use allMatch:

boolean result = l.stream().allMatch(s::contains);
Matted answered 18/5, 2018 at 18:54 Comment(0)
S
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
Spermatophyte answered 18/5, 2018 at 20:46 Comment(6)
just becomes you can use Set#containsAll doesnt mean there is no need to use a stream...Matted
@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.Spermatophyte
only worry about "overhead" when you notice a performance issue.Matted
@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?Sumikosumma
@Sumikosumma 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.Matted
I just don't think the remote possibility of OP needing to map-reduce warrants the use of a Stream in this case.Spermatophyte
M
8

You can use allMatch:

boolean result = l.stream().allMatch(s::contains);
Matted answered 18/5, 2018 at 18:54 Comment(0)
M
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);
Marplot answered 18/5, 2018 at 18:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.