【问题标题】:Inverse Map where getValue returns a ListgetValue 返回列表的逆映射
【发布时间】:2018-11-27 11:37:12
【问题描述】:

我想将Map<String, List<Object>> 转换为Map<String, String>。如果只是 Map<String, Object> 在 Java8 中很容易;

stream().collect(k -> k.getValue().getMyKey(), Entry::getKey);

但这不起作用,因为 getValue 在我的示例中返回一个 List Map<List<Object>, String>。假设 Object 包含一个用于键的 getter,并且 Object 不包含第一个映射中的键。

有什么想法吗?

【问题讨论】:

  • 你能解释一下吗...并且那个 Object 不包含第一个映射中的键。 ?

标签: java java-8 hashmap inverse


【解决方案1】:

流过对象列表并提取您需要的密钥然后map --> flatten --> toMap

source.entrySet()
      .stream()
      .flatMap(e -> e.getValue()
                     .stream()
                     .map(x -> new SimpleEntry<>(x.getMyKey(), e.getKey())))
      .collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));

如果预计会有重复的getMyKey() 值,请使用合并函数:

source.entrySet()
      .stream()
      .flatMap(e -> e.getValue()
                     .stream()
                     .map(x -> new SimpleEntry<>(x.getMyKey(), e.getKey())))
      .collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue, (l, r) -> l));

注意:以上使用源映射键作为结果映射的值,正如您在帖子中所说明的那样,如果您希望保留源映射的键作为结果映射的键,然后将new SimpleEntry&lt;&gt;(x.getMyKey(), e.getKey()) 更改为new SimpleEntry&lt;&gt;(e.getKey(),x.getMyKey())

【讨论】:

    【解决方案2】:

    如果偏好可以在映射为 key 的多个值中选择 any,您可以简单地使用:

    Map<String, List<YourObject>> existing = new HashMap<>();
    Map<String, String> output = new HashMap<>();
    existing.forEach((k, v) -> v.forEach(v1 -> output.put(v1.getMyKey(), k)));
    

    基本上这会将“第一个”这样的myKey 与其对应的值(即现有地图的key)放在一起。

    【讨论】:

      猜你喜欢
      • 2020-04-05
      • 2019-07-14
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多