Home > front end >  From if/else to Stream using Map.Entry
From if/else to Stream using Map.Entry

Time:10-15

Could you help me please conver from if/else to Stream

public Integer months() {
    
    String desiredObject;
    Map<String, Integer> monthDays = new HashMap<>();
    
    monthDays.put("March", 31);
    monthDays.put("April", 30);
    
    Set<Map.Entry<String, Integer>> entrySet = monthDays.entrySet();
    
    for (Map.Entry<String, Integer> pair : entrySet) {
        if (desiredObject.equals(pair.getKey())) {
            return pair.getValue();
        }
        
    }
}

CodePudding user response:

return entrySet.stream()
  .filter(pair -> desiredObject.equals(pair.getKey()))
  .map(Entry::getValue)
  .findAny().orElse(null);

or, alternatively just

return monthDays.get(desiredObject);
  • Related