我有地图的结构图,如:
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 ),就可以实现它的功能?
发布于 2018-11-13 21:39:45
不幸的是,如果您想继续您的流方法,则不可避免地要创建某种类型的中间对象,即Triple、AbstractMap.SimpleEntry或任何其他适用的类型。
您实际上是在寻找类似于C#的匿名类型的东西,也就是说,您只需映射到
new { k1 = entry.getKey(), k2 = e.getKey(), k3 = e.getValue()) }然后立即访问处于groupingBy和toMap阶段的用户。
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。
这里唯一的好处是您不需要预先定义一个自定义类。
发布于 2018-11-13 21:15:09
有些事情没有流更容易做:
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)));https://stackoverflow.com/questions/53289504
复制相似问题