简体   繁体   English

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

[英]Find a map in list of map java stream

I am iterating through a List of Hashmap to find the required HashMap object using the following code. 我正在迭代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;
}

I was thinking about using Java 8 stream. 我在考虑使用Java 8流。 This is the code I used to display the required object. 这是我用来显示所需对象的代码。

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

I couldn't get the required Map from the stream using following code 我无法使用以下代码从流中获取所需的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()));
}

This causes syntax error Type mismatch: cannot convert from Map to Map . 这会导致语法错误类型不匹配:无法从Map转换为Map What do I have to put here to get Map? 我有什么需要放在这里获取地图?

You don't want to .collect anything. 你不想。 .collect任何东西。 You want to find the first map that matches the predicate. 您想要找到与谓词匹配的第一个地图。

So you should use .findFirst() instead of .collect() . 所以你应该使用.findFirst()而不是.collect()

toMap() is for building a Map from the elements in the stream. toMap()用于从流中的元素构建Map

But you don't want to do that, each element is already a Map . 但是你不想这样做,每个元素都已经是一个Map

User this 用户这个

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

This will will work, the other examples without orElse() don't compile (at least they don't in my IDE). 这将是有效的,没有orElse()的其他示例不会编译(至少它们不在我的IDE中)。

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

The only thing I would add as a suggestion is to return Collections.emptyMap() , this will save a null check in the calling code. 作为建议我唯一要添加的是返回Collections.emptyMap() ,这将在调用代码中保存空检查。

To get the code to compile without orElse you need to change the method signature to: 要在没有orElse情况下编译代码,您需要将方法签名更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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