![](/img/trans.png)
[英]Convert Map<Integer, List<Object>> to Map<Integer, Map<String, Map<LocalDate, Integer>>> using Java stream API
[英]Java 8 stream Map<String, Map<String, Integer>> return map values if root map key contains
我有一张 map 地图:
Map<String, Map<String, Integer>> rootMap
如果rootMap
键包含使用 stream 的stringValue
,我想返回 rootMap 值Map<String, Integer>
。
我试过了:
rootMap.entrySet().stream().filter(e -> e.getKey().contains(stringValue)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
但我得到Map<Object, Object>
而不是Map<String, Integer>
更新#1
// it's a class with one field and a helper method
// @Data is a Lombok annotation
@Data
public class A {
public Map<String, Map<String, Integer>> rootMap;
public Map<String, Integer> getValuesByKey(String stringValue) {
return rootMap.entrySet().stream().filter(e -> e.getKey().contains(stringValue)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
}
这是你的表达:
rootMap.entrySet()
.stream()
.filter(e -> e.getKey().contains(stringValue))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
这是你的目标:
如果 rootMap 键包含使用 stream 的 stringValue,我想返回 rootMap 值 Map<String, Integer>。
回想一下,map 密钥必须是唯一的。 您不能拥有多个具有相同密钥的同一实例的Map.Entry
。 因此,可以获取rootMap
中值为stringValue
的key对应的Map<String, Integer>
,如下:
rootMap.entrySet()
.stream()
.filter(e -> e.getKey().equals(stringValue))
.map(e -> e.getValue())
.findAny()
.get();
为了防止在rootMap
中不存在密钥的情况下出现错误,您可以使用此版本:
rootMap.entrySet()
.stream()
.filter(e -> e.getKey().equals(stringValue))
.map(e -> e.getValue())
.findAny()
.orElse(Collections.emptyMap());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.