使用流将Map <A,Map <B,C >>转换为Map <B,Map <A,C >>

Paw*_*Bąk 3 java java-8 java-stream

我有地图的结构图,如:

Map<Center, Map<Product, Value>> given
Run Code Online (Sandbox Code Playgroud)

而且我想得到

Map<Product, Map<Center, Value>> result
Run Code Online (Sandbox Code Playgroud)

我使用过Java流

Map<Product, Map<Center, Value>> result = given.entrySet().stream()
        .flatMap(entry -> entry.getValue()
                 .entrySet().stream()
                 .map(e -> Triple(entry.getKey(), e.getKey(), e.getValue())))
        .collect(Collectors.groupingBy(Triple::getProduct,
                    Collectors.toMap(Triple::getCenter, Triple::getValue)));
Run Code Online (Sandbox Code Playgroud)

哪里Triple是简单的价值类.我的问题是,如果有可能做到这一点的功能,而无需使用额外的类,如Triple或如Table从番石榴?

shm*_*sel 7

如果没有流,有些事情更容易完成:

Map<Product, Map<Center, Value>> result = new HashMap<>();
given.forEach((c, pv) -> pv.forEach((p, v) ->
        result.computeIfAbsent(p, k -> new HashMap<>()).put(c, v)));
Run Code Online (Sandbox Code Playgroud)