Checking Map for two condtions using filter

Viewed 72

I have a map with collegeID and Student Id

I am checking if the Map has both the keys and values associated with them

This is always giving false

This is my code

Map<String, String> allDataMap = new HashMap<>();
allDataMap.put("college_id", "1095");
allDataMap.put("student_id", "108");

boolean present = allDataMap.entrySet().stream()
    .filter(map -> map.getKey().equals("college_id") && map.getValue().equals("1095"))
    .filter(map -> map.getKey().equals("student_id") && map.getValue().equals("108"))
    .findAny().isPresent() ? true : false;

System.out.println(present);
2 Answers

The two filters are mutual exclusive, so no element of your Stream can pass both of them. Therefore you get false.

You can use a single filter:

boolean present =  allDataMap.entrySet().stream()
    .filter(map-> (map.getKey().equals("college_id") && map.getValue().equals("1095")) || 
                  (map.getKey().equals("student_id") && map.getValue().equals("108")))
    .count() == 2;

Note that this relies on the source of the Stream being a Map, which means no key can appear twice, so if the Stream has exactly two elements after applying the filter, this means both key-value pairs appear in the source Map.

In general Streams this won't necessarily return the correct result, since the same key-value pair might appear twice.

You don't need a stream that at all, as @Thomas has pointed out in the comment.

Checking two values in a HashMap is a constant time O(1) action, but iterating over map entries takes O(n). And the latter option requires having the same conditional logic inside the stream. Definitely, employing a stream would buy you nothing in this case.

The following condition would be concise and straightforwards:

boolean present = "1095".equals(allDataMap.get("college_id"))
                && "108".equals(allDataMap.get("student_id"));

Note: if argument passed to the String.equals() is null, method call would return false.

Related