【问题标题】:HashMap transformation using streams使用流的 HashMap 转换
【发布时间】:2021-12-30 21:35:45
【问题描述】:

我有Map<Long, Map<String, String>> map,我必须通过键过滤它并进一步获得唯一值。 我正在尝试这样做:

Map<Object, Object> resultMap = map.entrySet().stream()
  .filter(x -> x.getKey().equals(filterValue))
  .map(Map.Entry::getValue).collect(Collectors.toMap(k -> k,v -> v));

但我得到的是Map&lt;Object, Object&gt; 地图而不是Map&lt;String, String&gt;

也许,有更好的方法来做到这一点。

【问题讨论】:

  • Map&lt;String, String&gt; result = foo.entrySet().stream().filter(x -&gt; x.getKey().equals(filterValue)).map(Entry::getValue).map(Map::entrySet).flatMap(Set::stream).collect(Collectors.toMap(Entry::getKey, Entry::getValue)); Ideone demo(请忽略运行时异常 - Ideone 应该证明编译通过)
  • 谢谢!这对我有用。

标签: java hashmap java-stream


【解决方案1】:

以下应该可以满足您的需要:

Map<String, String> resultMap = map.entrySet().stream()
    .filter(x -> x.getKey().equals(filterValue))
    .flatMap(entry -> entry.getValue().entrySet().stream())
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

【讨论】:

    【解决方案2】:

    您应该在收集器中将地图的值设置为特定类型

    .collect(Collectors.toMap(Object::toString, Object::toString))
    

    【讨论】:

      【解决方案3】:

      map.entrySet().stream().filter(x -&gt; x.getKey().equals(filterValue))可以理解为filterValue是一个long。无需流式传输映射以过滤掉与特定键匹配的值。因为映射键是唯一的,并且只有一个匹配键。您可以使用:

      Map<String, String> result = map.get(filterValue);
      

      【讨论】:

        猜你喜欢
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多