【问题标题】:Flatten the map and associate values using Java 8 Stream APIs使用 Java 8 Stream API 展平地图并关联值
【发布时间】:2016-02-18 07:06:48
【问题描述】:

假设我有一组字符串到整数值的映射:
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

x -> 2
y -> 2
z -> 3
u -> 4
v -> 4
w -> 4

它看起来像一个flatMap 操作,但我怎样才能将整数值与每个字符串键适当地关联起来呢?

【问题讨论】:

    标签: lambda functional-programming java-8 java-stream flatmap


    【解决方案1】:

    您可以像这样创建中间 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));
    

    或者,您可以使用项目中的任何其他对/元组类型。

    请注意,我的免费 StreamEx 库支持以更简洁的方式处理此类情况(内部与上述相同):

    Map<String, Integer> result = EntryStream.of(map).flatMapKeys(Set::stream).toMap();
    

    EntryStream 类扩展了 Stream&lt;Map.Entry&gt; 并提供了其他有用的方法,例如 flatMapKeystoMap

    【讨论】:

      猜你喜欢
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 2022-07-05
      • 2014-05-27
      • 2017-02-12
      相关资源
      最近更新 更多