Java 8 Strem filter map in map — Map<String,Map<String,Employee>>

  • A+
Category:Languages

How to filter a Map<String,Map<String,Employee>> using Java 8 Filter?

I have to filter only when any of employee in the list having a field value Gender = "M".

Input:

Map<String,Map<String,Employee>>

Output:

Map<String,Map<String,Employee>>

Filter criteria:

Employee.genter = "M"

Also i have to return empty map if the filtered result is empty.

I tried the below, but it is not working as expected. It is returning the only if all the Employees are with gender "M".

tempCollection.entrySet().stream()                         .filter(i -> i.getValue().entrySet().stream().allMatch(e-> "M".equals(e.getValue().getGender())))                         .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); 

 


You could simply iterate on the key-value pairs and filter as:

Map<String, Map<String, Employee>> output = new HashMap<>(); tempCollection.forEach((k, v) -> {     if (v.values().stream().anyMatch(i -> "M".equals(i.getGender()))) {         output.put(k, v.entrySet()                 .stream()                 .filter(i -> "M".equals(i.getValue().getGender()))                 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));     } }); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: