javadictionaryjava-8java-streamjava-11

Convert Map with Set of Strings as key to Map with Strings


The question is not difficult, and I have already solved it in my own way, but I would like to hear your opinion, maybe there is some way to make this an improved option? Java 8-11.

Map<Set<String>, User> --> Map<String, User>

Imagine, that elements inside of the set are won't repeat. One more note: many unique keys can point to the same value.

I made this with the following code:

Map<String, User> result = new HashMap<>();
existingMap.forEach((set, user) -> set.forEach(item -> result.put(set, user)));

So, my question is - is there a better way to do it? I mean, maybe Stream API already has some methods to do it? in the scope of 'collect' method


Solution

  • If you want to use a collector, you can do a flatMap first, then toMap:

    Map<String, User> result = existingMap.entrySet().stream().flatMap(
            entry -> entry.getKey().stream()
                .map(s -> Map.entry(s, entry.getValue()))
        )
        .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
    

    Or if you just want to use collect only (this is more similar to your original approach):

    Map<String, User> result = existingMap.entrySet().stream().collect(
        HashMap::new,
        (map, entry) -> entry.getKey().forEach(x -> map.put(x, entry.getValue())),
        HashMap::putAll
    );