我有像这样的 map 的结构图:
Map<Center, Map<Product, Value>> given
我想得到
Map<Product, Map<Center, Value>> result
我用过 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)));
其中 Triple
是简单值类。我的问题是是否可以在不使用 Triple
或例如Table
来自 Guava ?
最佳答案
没有流,有些事情更容易完成:
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)));
关于java - 使用流将 Map<A, Map<B, C>> 转换为 Map<B, Map<A, C>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53289504/