Paramesh Korrakuti
Paramesh Korrakuti

Reputation: 2067

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?

Upvotes: 14

Views: 29006

Answers (1)

Eran
Eran

Reputation: 393801

Use Collectors.toMap :

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

or

orders.stream().collect(Collectors.toMap(o -> o.getID(), o -> o.getSummary()));

Upvotes: 37

Related Questions