问题
我想使用Java 8的流和lambdas将对象列表转换为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 lambdas。
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
#1 热门回答(1005 赞)
基于“收集器”文档,简单如下:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName,
Function.identity()));
#2 热门回答(198 赞)
如果你的密钥is不guaranteed成为列表中的所有元素独特的,你应该把它转换成一个' Map <字符串,列表<选择>>',而不是' Map <字符串,选择>`
Map<String, List<Choice>> result =
choices.stream().collect(Collectors.groupingBy(Choice::getName));
#3 热门回答(104 赞)
使用getName()作为键和选择本身作为映射的值:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName, c -> c));