我想使用 Java 8 的流和 lambda 将对象列表转换为地图。
这就是我在 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);
}