javasetjava-stream

How to convert Set<Set<String>> to Set<String>?


Assuming that Streams and Collections, Lambdas are allowed to use? I tried using a for loop but it didn't solve my problem.

// Set<Set<String>> to Set<String>
for(Set<String> s : set) {
    result.addAll(s);
    set.add(result);
}

set is a Set<Set<String>> type and result is a type of Set<String>.


Solution

  • Here is the option using Stream API:

    Set<String> result = sets.stream()
        .flatMap(Collection::stream)
        .collect(Collectors.toSet());