我想使用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的情况下完成。
在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();
}
});
}
还有Java8 lambda的番石榴。
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
Maps.uniqueIndex(choices, Choice::getName)
。 - Bogdan CalmacSeq
(我建议所有使用Java 8的人都使用),你也可以通过以下方式改善简洁性:seq(choices).toMap(Choice::getName)
该语句的作用是将choices
序列转换为一个以Choice
对象的名称为键的映射表。 - lukensit -> it
。在此使用Function.identity()
主要是因为它在引用的文档中被使用,并且在编写时我对lambda表达式的了解只到这里。 - zapl