Sitemap
Athula

Athula

Implement multi-value map using Java 8

2 min readDec 23, 2023

HR manager of my company came to me one day and ask me to write a program to group employees who are having same birthday. She shared list of employee details such as name, address, and date of birth. So, I start writing the code by first defining Employee object.

public class Employee
{
private LocalDateTime dateOfBirth;
private String name;
private String address;
}

Then I started implementing grouping logic for list of given employees. My final target is to generate a Map where its key is birthday, and its value is list of employees matched for that date.

Press enter or click to view image in full size
Figure 1: Classic implementation

Above figure shows how we can implement the given requirement. It is working fine. But when you look at the code its subject to make more errors. Its bit difficult to maintain and understand the code.

Get Athula’s stories in your inbox

Join Medium for free to get updates from this writer.

Just try to move the cursor near highlighted if condition.

Press enter or click to view image in full size
Figure 2 : Classic implementation refactoring

You will notice that IDE itself suggest replacing it with computeIfAbsent method as in Figure 2. Let apply the change.

Press enter or click to view image in full size
Figure 3: Multi value map with java 8

Now you will notice that the logic we have written in the Figure 1 is more simplified in Figure 3. So computeIfAbsent has added employee by creating new Array list if key is not present. Otherwise, it has added employee to the existing list which is related to the key ( dateOfBirth in this case). And what we need to do is add our employee to the List.

Q&A:

  1. What will happen if key is absent?

If key is absent, it will call the function to compute the new value. In our case we asked to create new ArrayList().

2. What will happen if key is present?

If key is present in the map and it is non-null, the computeIfAbsent method does not execute the provided function. It simply returns the existing value associated with the key.

Cheers, happy coding.. 😊

--

--