简体   繁体   中英

Filter List<Map<String, String>> using streams

I need to filter a list List<Map<String, String> > by value (if map have searched value, then map add to list) using streams. I'm trying to do this:

static Map<String, String> map1 = new HashMap<>();
static Map<String, String> map2 = new HashMap<>();
static Map<String, String> map3 = new HashMap<>();

static {
    map1.put("key", "value");
    map1.put("key2", "value2");

    map2.put("key3", "value3");
    map2.put("key2", "value2");

    map3.put("key3", "value3");
    map3.put("key4", "value4");
}

public static void main(String[] args) {
    List<Map<String, String>> list = new ArrayList<>();
    Map<String, String> resultMap = new HashMap<>();

    list.add(map1);
    list.add(map2);
    list.add(map3);

    List<Map<String, String>> result = list.stream()
            .flatMap(map -> map.entrySet().stream())
            .filter(value -> value.getValue().equals("value2"))
            .map(x -> resultMap.put(x.getKey(), x.getValue()))
            .collect(Collectors.toList());

}

For execution this code i have error: java: incompatible types: inference variable T has incompatible bounds equality constraints: java.util.Map lower bounds: java.lang.String

If you want all the Map s of the input List that contain the "value2" value to appear in the output List , you need:

List<Map<String, String>> result = 
    list.stream()
        .filter(map -> map.entrySet().stream().anyMatch (e->e.getValue().equals("value2")))
        .collect(Collectors.toList());

Or (as Eritrean commented):

List<Map<String, String>> result = 
    list.stream()
        .filter(map -> map.containsValue("value2"))
        .collect(Collectors.toList());

Another quick solution is removeIf function. Has the advantage of reusing the same list object.

 list.removeIf(map -> !map.containsValue("value2"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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