问题:
I want to translate a List of objects into a Map using Java 8's streams and lambdas. 我想使用Java 8的流和lambda将对象列表转换为Map。
This is how I would write it in Java 7 and below. 这就是我在Java 7及以下版本中编写它的方式。
private Map<String, Choice> nameMap(List<Choice> choices) {
final Map<String, Choice> hashMap = new HashMap<>();
for (final Choice choice : choices) {
hashMap.put(choice.getName(), choice);
}
return hashMap;
}
I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava. 我可以使用Java 8和Guava轻松完成此操作,但是我想知道如何在没有Guava的情况下执行此操作。
In Guava: 在番石榴:
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, new Function<Choice, String>() {
@Override
public String apply(final Choice input) {
return input.getName();
}
});
}
And Guava with Java 8 lambdas. 带有Java 8 lambda的番石榴。
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
解决方案:
参考一: https://stackoom.com/question/1NRX5/Java-清单-V-进入地图-K-V参考二: https://oldbug.net/q/1NRX5/Java-8-List-V-into-Map-K-V
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/4319374