1

Code Template:

Map<String, String> hashMap = new HashMap<>();    
hashMap.put("RED", "1");    
hashMap.put("BLUE", "2");    
hashMap.put("BLACK", "3");    

Map<String, String> filteredMap = hashMap.entrySet().stream()
.filter(entry -> (entry.getKey().equals("RED") && entry.getValue().equals("1"))  
**&&**
(entry.getKey().equals("BLUE") && entry.getValue().equals("2")) )
.collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));

I want to find if the Map contains both {Red,1} and {Blue,2} inside it. How do I put both filters condition in a stream? I tried with && condition, but it's not working. Kindly help.

3 Answers 3

4

Why do you want to use filter here at all? The filter over stream of entries shown in the question iterates through all the members of the map ( O(n) ) However, the HashMap guarantees O(1) access to "get" functionality. So why sacrifice performance here?

If you want to check whether the map contains a key (ok, two keys), why not simply:

if("1".equals(hashMap.get("RED")) && "2".equals(hashMap.get("BLUE"))) {
   // yes, this map indeed contains both elements 
   // in case the "RED" is not in the map, the call to "get" will return null
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Mark. You are amazing! :)
2

Streams are not really appropriate for your problem. They are great for performing independent operations on members of a collection and then aggregating the results in some way. They are not great for functions on the collection as a whole or algorithms requiring interaction between members.

A much simpler formulation would be:

Objects.equals(map.get("RED"), "1") && Objects.equals(map.get("BLUE"), "2")

An alternative that avoids hardcoding the comparison would be:

Map<String, String> reference = Map.of("RED", "1", "BLUE", "2");

if (hashMap.entrySet().containsAll(reference.entrySet()) {
    ...
}

1 Comment

Thanks, sprinter. You are amazing! :)
0

You can put both consitions in one filter itself

    Map<String, String> hashMap = new HashMap<>();
    hashMap.put("RED", "1");
    hashMap.put("BLUE", "2");
    hashMap.put("BLACK", "3");

    Map<String, String> filteredMap = hashMap.entrySet().stream()
            .filter(entry -> (entry.getKey().equals("RED") && entry.getValue().equals("1")
                    || (entry.getKey().equals("BLUE") && entry.getValue().equals("2"))))
            .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));
    System.out.println(filteredMap);

1 Comment

Thanks Bhushan. You are amazing! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.