Home > Enterprise >  Java 8 Stream Filter Map With Multiple condition
Java 8 Stream Filter Map With Multiple condition

Time:12-15

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.

CodePudding user response:

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
}

CodePudding user response:

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()) {
    ...
}
  • Related