【问题标题】:how to convert a hashmap of list into a single list in Java 8?如何将列表的哈希图转换为 Java 8 中的单个列表?
【发布时间】:2018-04-05 22:35:20
【问题描述】:

我对 java 8 完全陌生,我有点不清楚如何继续。 我在 Java 7 中有一个 Map <String, List<value>>,我只会在键上使用 for 循环并将列表收集到一个列表中。

但是,我希望能够在 8 中做到这一点。 我所拥有的是:

List<Value> newList = resultMap.entrySet().stream()
                       .flatMap( e -> e.getValue().stream())
                       .map( // get the value in the list)
                       .collect(Collectors.toList())

但是,在这种情况下,我无法从 value 所属的 hashmap 中知道 key。

在执行上述操作时,如何获取 hashmap 的键值?

【问题讨论】:

  • for 循环中的代码是什么样的?我想知道您如何处理密钥,因为您没有将其放入结果列表中。
  • 对于他们的密钥,您将使用keySet 而不是entrySet;请说明resultMap 的类型以及您期望在newList 中的类型。
  • List values = map.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
  • @CardinalSystem OP 说 Map 的类型应该类似于 Map&lt;?, List&lt;Value&gt;&gt; 所以你不能直接在 Map 的值上使用 Collectors.toList()
  • 钥匙丢弃后无法取回。您的flatMap lambda 必须保留您以后想要的任何信息。

标签: java dictionary streaming flatmap


【解决方案1】:

你可以这样做:

Map<Key, List<Value>> map = ...;

List<Map.Entry<Key, Value>> list =
    map.entrySet()
        .stream()
        .flatMap(e -> {
          return e.getValue().stream()
              .map(v -> new AbstractMap.SimpleEntry<>(e.getKey(), v));
        })
        .collect(Collectors.toList());

这将为每个子列表中的每个值创建一个条目,其中键是该值来自的列表的对应键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    相关资源
    最近更新 更多