Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a HashMap using a Lambda Expression

There is one class (SomeOrders), which has few fields like Id, Summary, Amount, etc...

The requirement is to collect Id as key and Summary as value to a HashMap from an input List of SomeOrder objects.

Code in Before java 8:

List<SomeOrder> orders = getOrders();
Map<String, String> map = new HashMap<>();
for (SomeOrder order : orders) {
    map.put(order.getId(), order.getSummary());
}

How to achieve the same with Lambda expression in Java 8?

like image 743
Paramesh Korrakuti Avatar asked Mar 23 '15 10:03

Paramesh Korrakuti


People also ask

How do you add an element to a HashMap?

To add elements to HashMap, use the put() method.

How do you iterate through a list in lambda expression?

Iterable. forEach() Since Java 8, we can use the forEach() method to iterate over the elements of a list. This method is defined in the Iterable interface, and can accept Lambda expressions as a parameter.

Can lambda expression contain data type?

The lambda expressions have a very simple, precise syntax and provide flexibility to specify the datatypes for the function parameters.


1 Answers

Use Collectors.toMap :

orders.stream().collect(Collectors.toMap(SomeOrder::getID, SomeOrder::getSummary));

or

orders.stream().collect(Collectors.toMap(o -> o.getID(), o -> o.getSummary()));
like image 54
Eran Avatar answered Oct 26 '22 23:10

Eran