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?
To add elements to HashMap, use the put() method.
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.
The lambda expressions have a very simple, precise syntax and provide flexibility to specify the datatypes for the function parameters.
Use Collectors.toMap :
orders.stream().collect(Collectors.toMap(SomeOrder::getID, SomeOrder::getSummary));
or
orders.stream().collect(Collectors.toMap(o -> o.getID(), o -> o.getSummary()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With