liuwei7923 liuwei7923 - 7 months ago 33
Java Question

Java8: How to Convert Map<X, List<Y>> to Map<Y,X> using Stream?

I am new to Java8. A problem that I want to solve is to convert Map> to Map using Stream. For example:

input: {A => [B, C, D], E => [F]}
output: {B => A, C => A, D => A, F => E}

Let's assume that there is no duplicated value in List. How to do it in java 8 stream in an elegant way?




    Map<String, List<Integer>> map = new HashMap<>();
    Map<Integer,String>        pam = new HashMap<>();

This will do what you want

    map.entrySet().stream().forEach(e -> e.getValue().stream().forEach(v -> pam.put(v, e.getKey())));

This takes advantage of the fact that Set<E> implements stream() from Collection. The rest is just plugging things into the right place.

Or, as suggested by @user140547 (thank you), an even simpler solution

    map.forEach((k,v) -> v.forEach(vv -> pam.put(vv, k)));