代码之家  ›  专栏  ›  技术社区  ›  Thilo

如何构建一个Java`Map<K,V>`out`列表<地图。入口<K,V>>`?[复制]

  •  -1
  • Thilo  · 技术社区  · 7 年前

    我有一个 List<Map.Entry<Long, String>> .

    如何将其转换为 Map ?

    Map<Long, String> result = new HashMap<>();
    entries.forEach(e -> result.put(e.getKey(), e.getValue()));
    return result;
    

    Java 10很好。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Eran    7 年前

    如果您确定没有重复的密钥,这就足够了:

    Map<Long, String> result = entries.stream().collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
    

        2
  •  2
  •   Andy Turner    7 年前

    压平它:

    Map<Long, String> result = 
        entries.stream()
            .collect(toMap(e -> e.getKey(), e -> e.getValue(), (a, b) -> b);
    

    这个 (a, b) -> b 意味着将采用重复键的最后一个值,该值与当前方法的语义相匹配。