0
votes

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

2
Does this approach work? If not, do you get an error? Or do you get an unexpected result? Which?user11044402

2 Answers

2
votes

If you want all the Maps 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());
0
votes

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

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