14

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?

3
  • 1
    possible duplicate of Java: How to convert List to Map Commented Mar 23, 2015 at 11:06
  • 1
    Yes, almost same. stackoverflow.com/questions/4138364/… But above is just asked in general, from that one answer can find with Lambda expression. Anyhow thanks for notifying me. Commented Mar 23, 2015 at 11:09
  • Don't get confuse among lambda expression and stream functional operations. I think you would like to get answer for functional operations, as the answer below. Commented Oct 4, 2017 at 3:11

1 Answer 1

37

Use Collectors.toMap :

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

or

orders.stream().collect(Collectors.toMap(o -> o.getID(), o -> o.getSummary())); 
Sign up to request clarification or add additional context in comments.

2 Comments

What if the orders list has duplicates and the map should have a List to collect the order summaries ? List<> to Map<String, List<String>>
How to populate an EnumMap like this ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.