Reputation: 275
Imagine a collection of collections(set of sets):
Set<Set<Long>> setOfSets = new HashSet<>();
Set<Long> set = new HashSet<>();
set.add(4L);
set.add(3L);
set.add(8L);
setOfSets.add(set);
set = new HashSet<>();
set.add(6L);
set.add(7L);
set.add(4L);
setOfSets.add(set);
How do I remove given value from this collection using java streams? For example if the given value is 4 then expected sets should be equal to {[3, 8][6, 7]}. I know that this is possible with iterating through the collection(s) using nested for loops, but I'm specifically interested in using streams.
Upvotes: 2
Views: 78
Reputation: 11483
Since they're pass-by-reference, you can just mutate them directly:
int removeNum = 4;
setOfSets.forEach(s -> s.remove(removeNum));
//add it to each
setOfSets.forEach(s -> s.add(removeNum));
While it isn't technically a stream solution, it's pretty much along those lines.
Upvotes: 1
Reputation: 1183
Set<Set<Long>> result = setOfSets.stream()
.map(s -> s.stream()
.filter(id -> (id != 4L))
.collect(Collectors.toSet()))
.collect(Collectors.toSet());
Upvotes: 1