使用 Java 8 个流 API 展平地图和关联值
Flatten the map and associate values using Java 8 Stream APIs
假设我有一组字符串到整数值的映射:
Map<HashSet<String>, Integer> map = new HashMap<>()
。
例如,map
是(我们假设没有重复的字符串):
{x,y} -> 2
{z} -> 3
{u,v,w} -> 4
如何使用 Java 8 个 Stream API[= 如下获取 Map<String, Integer>
类型的 another_map
32=]:
x -> 2
y -> 2
z -> 3
u -> 4
v -> 4
w -> 4
它看起来像一个 flatMap
操作,但我如何才能将 Integer 值与每个 String 键适当地关联起来?
您可以像这样创建中间 Map.Entry
对象:
Map<String, Integer> result = map.entrySet().stream()
.<Entry<String, Integer>>flatMap(entry ->
entry.getKey()
.stream()
.map(s -> new AbstractMap.SimpleImmutableEntry<>(s, entry.getValue())))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
或者,您可以使用项目中的任何其他 pair/tuple 类型。
请注意,我的免费 StreamEx 库支持以更简洁的方式处理此类情况(内部与上述相同):
Map<String, Integer> result = EntryStream.of(map).flatMapKeys(Set::stream).toMap();
EntryStream
class extends Stream<Map.Entry>
and provides additional helpful methods like flatMapKeys
or toMap
.
假设我有一组字符串到整数值的映射:
Map<HashSet<String>, Integer> map = new HashMap<>()
。
例如,map
是(我们假设没有重复的字符串):
{x,y} -> 2
{z} -> 3
{u,v,w} -> 4
如何使用 Java 8 个 Stream API[= 如下获取 Map<String, Integer>
类型的 another_map
32=]:
x -> 2
y -> 2
z -> 3
u -> 4
v -> 4
w -> 4
它看起来像一个 flatMap
操作,但我如何才能将 Integer 值与每个 String 键适当地关联起来?
您可以像这样创建中间 Map.Entry
对象:
Map<String, Integer> result = map.entrySet().stream()
.<Entry<String, Integer>>flatMap(entry ->
entry.getKey()
.stream()
.map(s -> new AbstractMap.SimpleImmutableEntry<>(s, entry.getValue())))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
或者,您可以使用项目中的任何其他 pair/tuple 类型。
请注意,我的免费 StreamEx 库支持以更简洁的方式处理此类情况(内部与上述相同):
Map<String, Integer> result = EntryStream.of(map).flatMapKeys(Set::stream).toMap();
EntryStream
class extends Stream<Map.Entry>
and provides additional helpful methods like flatMapKeys
or toMap
.