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

我有地图的结构图,例如:


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番石榴)的情况下实现它的功能?


喵喔喔
浏览 249回答 2
2回答

湖上湖

没有流,有些事情会更容易完成:Map<Product, Map<Center, Value>> result = new HashMap<>();given.forEach((c, pv) -> pv.forEach((p, v) ->&nbsp; &nbsp; &nbsp; &nbsp; result.computeIfAbsent(p, k -> new HashMap<>()).put(c, v)));

DIEA

不幸的是,如果您想继续使用流方法,则不可避免地要创建某种类型的中间对象Triple,即 ie 或AbstractMap.SimpleEntry任何其他适用的类型。您实际上是在寻找类似 C# 的匿名类型的东西,即您可以映射到new { k1 = entry.getKey(), k2 = e.getKey(), k3 = e.getValue()) }然后立即访问groupingByandtoMap阶段的那些。Java有类似但不完全的东西,你可以这样做:Map<Product, Map<Center, Value>> result =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;given.entrySet()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .flatMap(entry -> entry.getValue()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .entrySet().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(e -> new Object() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Center c = entry.getKey();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Product p = e.getKey();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Value v = e.getValue();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(o -> o.p, Collectors.toMap(o -> o.c, o -> o.v)));&nbsp;归功于@shmosel。唯一的好处是您不需要预定义自定义类。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java