computeIfAbsent() of HashMap in java8




Java 8 has many newly introduced features like lambda expression, stream api, default method, functional interface, methods and more. Method computeIfAbsent is one of them. If You are playing with a hashmap, and you are getting value based on key provided, and you need to to put value if map does not have provided key.You can use java8 computeIfAbsent to handle such cases now. We have a map which contains employee id and contains value which is a list of projects they are working in their organization. To know that each employee working on some project, we will check given map. If employee id is not there, we would create a list of projects, and add it to map. Before JAVA8 we'd write something like this:


 private final Map<String, List<Project>> employeesProjectsDetails = new HashMap<>();

 private void checkEmployeeProjects(String employeeId){
    List<Project> employeeProjects = employeeProjectsDetails.get(employeeId);
  
    if(employeeProjects == null)
      {
         // Method to give a list of projects for new employee
          employeeProjects == EmlpoyeesProjects.getEmployeeProjects(employeeId);
         // adding details to map
         employeesProjectsDetails.put(employeeId, employeeProjects); 
      }
     }

Now using computeIfAbsent() method:


private final Map<String, List<Project>> employeesProjectsDetails = new HashMap>();

private void checkEmployeeProjects(String employeeId){
   // using computeIfAbsent to check availability of employee, and lambda to get a lsit of projects for given employee
    List<Project> employeeProjects = employeeProjectsDetails.computeIfAbsent(employeeId, employeeId -> EmployeesProects.getEmployeeProjects);
   }

That's how you can use computeIfAbsent in your java code.