我想使用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);
}
groupingBy
创建的是一个Map<K,List<V>>
,而不是一个Map<K,V>
。 - Christoffer HammarströmString getName();
(不是Integer)。 - Barett