13

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?

Eran
  • 387,369
  • 54
  • 702
  • 768
Paramesh Korrakuti
  • 1,997
  • 4
  • 27
  • 39
  • 1
    possible duplicate of [Java: How to convert List to Map](http://stackoverflow.com/questions/4138364/java-how-to-convert-list-to-map) – Alexis C. Mar 23 '15 at 11:06
  • 1
    Yes, almost same. http://stackoverflow.com/questions/4138364/java-how-to-convert-list-to-map But above is just asked in general, from that one answer can find with Lambda expression. Anyhow thanks for notifying me. – Paramesh Korrakuti Mar 23 '15 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. – Alex Oct 04 '17 at 03:11

1 Answers1

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()));
buræquete
  • 14,226
  • 4
  • 44
  • 89
Eran
  • 387,369
  • 54
  • 702
  • 768