简体   繁体   中英

Remove some values from collection of collections using java streams

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.

Set<Set<Long>> result = setOfSets.stream()
                                 .map(s -> s.stream()
                                            .filter(id -> (id != 4L))
                                            .collect(Collectors.toSet()))
                                 .collect(Collectors.toSet());

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM