2 回答

TA贡献2003条经验 获得超2个赞
没有流,有些事情会更容易完成:
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)));

TA贡献1820条经验 获得超3个赞
不幸的是,如果您想继续使用流方法,则不可避免地要创建某种类型的中间对象Triple,即 ie 或AbstractMap.SimpleEntry任何其他适用的类型。
您实际上是在寻找类似 C# 的匿名类型的东西,即您可以映射到
new { k1 = entry.getKey(), k2 = e.getKey(), k3 = e.getValue()) }
然后立即访问groupingByandtoMap阶段的那些。
Java有类似但不完全的东西,你可以这样做:
Map<Product, Map<Center, Value>> result =
given.entrySet()
.stream()
.flatMap(entry -> entry.getValue()
.entrySet().stream()
.map(e -> new Object() {
Center c = entry.getKey();
Product p = e.getKey();
Value v = e.getValue();
}))
.collect(Collectors.groupingBy(o -> o.p, Collectors.toMap(o -> o.c, o -> o.v)));
归功于@shmosel。
唯一的好处是您不需要预定义自定义类。
添加回答
举报