java 如何使用 Lambda 表达式填充 HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29207744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to populate a HashMap using a Lambda Expression
提问by Paramesh Korrakuti
There is one class (SomeOrders
), which has few fields like Id
, Summary
, Amount
, etc...
还有一类(SomeOrders
),它具有像几个字段Id
,Summary
,Amount
,等...
The requirement is to collect Id
as key and Summary
as value to a HashMap
from an input List
of SomeOrder
objects.
要求是从对象输入中Id
作为键和Summary
值收集到 a 。HashMap
List
SomeOrder
Code in Before java 8:
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?
如何在 Java 8 中使用 Lambda 表达式实现相同的目标?
回答by Eran
Use Collectors.toMap
:
使用Collectors.toMap
:
orders.stream().collect(Collectors.toMap(SomeOrder::getID, SomeOrder::getSummary));
or
或者
orders.stream().collect(Collectors.toMap(o -> o.getID(), o -> o.getSummary()));