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

3

我正在使用以下代码遍历哈希映射列表,以查找所需的哈希映射对象。

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

我无法使用以下代码从流中获取所需的Map。
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。我需要在这里放什么才能得到Map?


1
mapList.stream().filter(e -> e.get("ip").equals(currentIp)).findFirst() ... 请注意,这将返回一个 Optional<Map ...>。 - griFlo
3
考虑定义类,而不是嵌套集合。很难理解List<Map<Set<String>, Map<Integer, List<HttpClient>>>>代表什么意思。 - Michael
3个回答

7

您不想使用.collect方法。您希望找到符合条件的第一个映射。

因此,您应该使用.findFirst()而不是.collect()

toMap()用于在流中构建一个Map

但您不想这样做,因为每个元素已经是一个Map


1
如果不需要顺序,可以使用findAny() - Lino
我接受了 @Andrew 的回答,因为它完全将我的 for 循环方法转换为带有 else null 的流。谢谢。 - Muneeb Mirza
1
@MuneebMirza 没问题。 :) 我建议你返回 Optional<Map<String,String>> 而不是 .orElse(null)。你到底对返回的 null 做了什么? - Christoffer Hammarström
1
@ChristofferHammarström 所以您的意思是我应该在findFirst()处返回?是的,我认为这样更合理。谢谢 :) - Muneeb Mirza

1
使用此用户
    public static Map<String, String> extractMapByStream(List<Map<String, String>> mapList, String currentIp) {
        return mapList.stream().filter(e -> e.get("ip").equals(currentIp))
            .findFirst().get();
}

编译器错误:类型 Optional<Map<String,String>> 不可分配给类型 Map<String,String> - Lino
1
这是因为findFirst()返回Optional类型,我们必须调用get()方法。我已经更新了答案。 - Rishikesh Dhokare
@RishikeshDhokare 不,如果你不确定Optional是否非空,就不要盲目调用.get()。那样会失去Optional的意义。 - Christoffer Hammarström

1
这将起作用,其他没有使用 orElse() 的示例无法编译(至少在我的IDE中不能)。
mapList.stream()
    .filter(asd -> asd.get("ip").equals(currentIp))
    .findFirst()
    .orElse(null);

我建议添加的唯一一件事情是返回 Collections.emptyMap(),这将在调用代码中节省一个空检查。

要使代码在不使用 orElse 的情况下编译,您需要更改方法签名为:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接