Java 8列表<V>到地图<K,V>我希望使用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);}
3 回答

浮云间
TA贡献1829条经验 获得超4个赞
Collectors
Map<String, Choice> result = choices.stream().collect(Collectors.toMap(Choice::getName, Function.identity()));

当年话下
TA贡献1890条经验 获得超9个赞
Map<String, List<Choice>>
Map<String, Choice>
Map<String, List<Choice>> result = choices.stream().collect(Collectors.groupingBy(Choice::getName));

慕田峪7331174
TA贡献1828条经验 获得超13个赞
Map<String, Choice> result = choices.stream().collect(HashMap<String, Choice>::new, (m, c) -> m.put(c.getName(), c), (m, u) -> {});
添加回答
举报
0/150
提交
取消