【发布时间】:2013-12-20 06:02:55
【问题描述】:
我想使用 Java 8 的流和 lambda 将对象列表转换为 Map。
这就是我在 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;
}
我可以使用 Java 8 和 Guava 轻松完成此任务,但我想知道如何在没有 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();
}
});
}
以及带有 Java 8 lambda 的 Guava。
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
【问题讨论】:
标签: java lambda java-8 java-stream