As a developer, the need to convert List to Map in Java is a common task. There are mainly two things that we want to achieve while converting to Map.
- Converting to map by making some property as a Key and an Object as a Value or
- Grouping the list by some property
In this post, we will learn both ways of converting List to Map in Java.
Let’s take an example of the following class and learn to convert List to Map
public class Customer {
private Long id;
private Long name;
private Country country;
// Other properties
}
Let’s assume we have a list of customer object like below.
List<Customer> customers;
Converting to map by making some property as a Key and an Object as a Value
Our expected output is the following:
Map<Long, Customer> idCustomerMap;
Before Java 8
Converting List to Map before Java 8 was
Map<Long, Customer> idCustomerMap = new HashMap<>();
for(Customer customer: customers){
// here making id as a key and customer object as a value
idCustomerMap.put(customer.getId(), customer);
}
After Java 8
Here, we can use Java Stream API along with Lamda expression.
Map<Long, Customer> idCustomerMap = customers.stream().collect(Collectors.toMap(Customer::getId, customer -> customer));
With these examples above, we have successfully converted a List to a Map.
Now, let’s look at the second approach.
Grouping the list by some property
Our expected output is
Map<Country, List<Customer>> countryCustomersMap;
The above map groups all the customers by country.
Before Java 8
In the below code, we are going to do the following steps inside our loop:
- Checking the map whether it contains the key country or not
- If the country is found on the map it means it already has a list of customers associated with this country
- Then, extract the list of customers associated with the country
- Add new customers to that list and
- Put this new list to map for the same country as a key
- If the country is not found on the map, that means this country is new and w need to add it to map
- Then, create a new list of customers
- Add new customers to that list
- Put this new list to map for the new country as a key
Let’s see the code below.
Map<Country, List<Custome>> countryCustomersMap = new HashMap<>();
for(Customer customer: customers){
if(countryCustomersMap.containsKey(customer.getCountry())){
List<Customer> customerList = countryCustomersMap.get(customer.getCountry());
customerList.add(customer);
countryCustomersMap.put(customer.getCountry(), customerList);
}else{
List<Customer> customerList = new ArrayList<>();
customerList.add(customer);
countryCustomersMap.put(customer.getCountry(), customerList);
}
}
After Java 8
Map<Country, List<Customer>> countryCustomersMap= customers.stream().collect(Collectors.groupingBy(Customer::getId));
Conclusion
We have successfully converted List to Map in Java without using any third-party library. We also learn, how we used to create a Map and the new way of creating it.