Skip to content
Advertisement

Java: join the values of a map containing sets

Consider the following pseudo Map<String, Set<String>>:

JavaScript

What is the best way to join the value Sets into a single Set (above example should be ["A", "B", "C", "D"]). The order of the resulting set does not matter.

I know that I can to something like this:

JavaScript

But it feels kind of ugly and I’m wondering if there is a better (and more “built-in”) way of doing this?

Advertisement

Answer

Use the Set.addAll(Collection) method; see the javadoc.

JavaScript

The logic should be self-evident.

Meta-lesson: it is a good idea to familiarize yourself with the capabilities of the APIs that you use by skim-reading the javadocs.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement