繁体   English   中英

Java 8 stream Map <string, map<string, integer> &gt; 如果根 map 密钥包含,则返回 map 值</string,>

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM