切换地图地图中的键

时间:2017-09-28 05:05:31

标签: java lambda functional-programming java-8

您如何使用Java 8流在此地图中交换密钥?或者至少清理一下这个烂摊子......

    Map<Type1, Map<Type2, String>> to Map<Type2, Map<Type1, String>>

使用嵌套for循环(未经测试):

    Map<Type1, Map<Type2, String>> map ...
    Map<Type2, Map<Type1, String>> map2 = new HashMap<>();
        for (Type 1 type1 : map.keySet()) {
            for(Entry<Type2, String> entry : map.get(type1)) {
                if (map2.get(entry.key() == null) {
                    map2.push(entry.key(), new HashMap<Type1, String>();
             } 
             map2.get(entry.key()).put(type1, entry.value();
        }
    }

到目前为止,我认为您需要将map映射到Type1,Type2和String的所有唯一组合,并将此集存储在某种中间集合中。

绝对错误:

map.entrySet().stream().flatMap(t -> <Type1, Type2, 
String>).collect(Collectors.toMap(t -> t.Type2, Collectors.toMap(t -> 
t.type1, t->t.String))

3 个答案:

答案 0 :(得分:2)

我会避开这类问题的流。这只是一个难以阅读的混乱。相反,请考虑使用其他Java 8添加内容简化代码 - Map#forEachMap#computeIfAbsent

map.forEach( (t1, e) -> 
    e.forEach( (t2, v) ->
            result.computeIfAbsent(t2, x -> new HashMap<>()).put(t1, v)
    )
);

答案 1 :(得分:2)

TreeCell已经向您展示了直接的解决方案。如果你真的想使用Stream,它可能看起来像这样:

public static <S, T> Map<T, Map<S, String>> convertStream(Map<S, Map<T, String>> map) {
  return map.entrySet().stream().flatMap(m1 -> m1.getValue().entrySet()
                                                 .stream().map(e -> new Object() {
    final T outer = e.getKey();
    final Map<S, String> map;
    {
      map = new HashMap<>();
      map.put(m1.getKey(), e.getValue());
    }
  })).collect(Collectors.toMap(o -> o.outer, o -> o.map, (m1, m2) -> {
    m1.putAll(m2);
    return m1;
  }));
}

答案 2 :(得分:0)

    Map<Type2, Map<Type1, Object>> finalAnswer = map.entrySet().stream()
.collect(()->new HashMap<Type2,Map<Type1,Object>>(),
            (mapAccumulator, left)->{               
                for(Entry<?, ?> leftEntry : left.getValue().entrySet() ){
                    Map<Type1,Object> tempMap = new HashMap<>();
                    tempMap.put(left.getKey(), leftEntry.getValue());
                    mapAccumulator.put((Type2) leftEntry.getKey(), tempMap);
                }

            /*accumulator*/},
        (mapLeft,mapRight)->{mapLeft.putAll(mapRight); /*combiner*/});

map.entrySet().forEach(System.out::println);