我希望使用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轻松地完成这一任务,但是我想知道如何在没有番石榴的情况下做到这一点。
在番石榴:
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羔羊。
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
发布于 2013-12-03 23:30:58
基于文档,它非常简单,如:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName,
Function.identity()));
发布于 2014-08-22 18:20:22
如果您的密钥是,而不是,则应该将其转换为Map<String, List<Choice>>
而不是Map<String, Choice>
。
Map<String, List<Choice>> result =
choices.stream().collect(Collectors.groupingBy(Choice::getName));
发布于 2015-02-28 07:18:15
使用getName()
作为键,使用Choice
本身作为映射的值:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName, c -> c));
https://stackoverflow.com/questions/20363719
复制相似问题