在地图Java流列表中查找地图

Muneeb Mirza:

我正在遍历Hashmap列表,以使用以下代码查找所需的HashMap对象。

public static Map<String, String> extractMap(List<Map<String, String>> mapList, String currentIp) {
    for (Map<String, String> asd : mapList) {
        if (asd.get("ip").equals(currentIp)) {
            return asd;
        }
    }
    return null;
}

我当时正在考虑使用Java 8流。这是我用来显示所需对象的代码。

public static void displayRequiredMapFromList(List<Map<String, String>> mapList, String currentIp) {
    mapList.stream().filter(e -> e.get("ip").equals(currentIp)).forEach(System.out::println);
}

我无法使用以下代码从流中获取所需的地图

public static Map<String, String> extractMapByStream(List<Map<String, String>> mapList, String currentIp) {
    return mapList.stream().filter(e -> e.get("ip").equals(currentIp))
            .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
}

这会导致语法错误类型不匹配:无法从Map转换为Map我必须在这里放置什么才能获得地图?

安德鲁 :

这将起作用,其他orElse()没有编译的示例(至少在我的IDE中不编译)。

mapList.stream()
    .filter(asd -> asd.get("ip").equals(currentIp))
    .findFirst()
    .orElse(null);

我建议添加的唯一内容是return Collections.emptyMap(),这将在调用代码中保存一个空检查。

要使代码得以编译而orElse无需将方法签名更改为:

public static Optional<Map<String, String>> extractMap(List<Map<String, String>> mapList, String currentIp)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章