# 拼合一个地图<整数，列表<字符串>>地图<字符串，整数>用流和lambda

Vongo：

``````Map<Integer, List<String>> mapFrom = new HashMap<>();
``````

``````1: a,b,c
2: d,e,f
etc.
``````

``````a: 1
b: 1
c: 1
d: 2
e: 2
f: 2
etc.
``````

``````Map<String, Integer> mapTo = new HashMap<>();
for (Map.Entry<Integer, List<String>> entry: mapFrom.entrySet()) {
for (String s: entry.getValue()) {
mapTo.put(s, entry.getKey());
}
}
``````

``````Map<String, Integer> mapTo = mapFrom.entrySet().stream().map(e -> {
e.getValue().stream().?
// Here I can iterate on each List,
// but my best try would only give me a flat map for each key,
// that I wouldn't know how to flatten.
}).collect(Collectors.toMap(/*A String value*/,/*An Integer key*/))
``````

• 是否有可能使用`streams``lambda`实现这一目标？
• 才是有用的（性能，可读性），这样做呢？

``````Map<String, Integer> mapTo = mapFrom.entrySet().stream()
.flatMap(e->e.getValue().stream()
.map(v->new AbstractMap.SimpleImmutableEntry<>(e.getKey(), v)))
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
``````

`Map.Entry`是一个独立的为不存在的元组类型，能够保持不同类型的两个对象的任何其它类型的是足够的。

``````Map<String, Integer> mapTo = mapFrom.entrySet().stream().collect(
HashMap::new, (m,e)->e.getValue().forEach(v->m.put(v, e.getKey())), Map::putAll);
``````

``````Map<String, Integer> mapTo = new HashMap<>();
mapFrom.forEach((k, l) -> l.forEach(v -> mapTo.put(v, k)));
``````

0 条评论