使用流的 HashMap 转换

HashMap transformation using streams

我有 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<Object, Object> 地图而不是 Map<String, String>

也许,有更好的方法。

您应该在收集器中将映射值设置为特定类型

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

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

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));

map.entrySet().stream().filter(x -> x.getKey().equals(filterValue))可以理解为filterValue是一个long。无需流式传输地图来过滤出与特定键匹配的值。因为map key是唯一的,匹配的key只会有一个。您可以使用:

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