我想使用 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的情况下做到这一点。
在番石榴:
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();
}
});
}
还有番石榴与爪哇 8 lambdas。
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
网友回答:
如果您的键不能保证对于列表中的所有元素都是唯一的,则应将其转换为 a 而不是Map<String, List<Choice>>
Map<String, Choice>
Map<String, List<Choice>> result =
choices.stream().collect(Collectors.groupingBy(Choice::getName));
网友回答:
根据文档,它非常简单:Collectors
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName,
Function.identity()));
网友回答:
用作键,将自身用作映射的值:getName()
Choice
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName, c -> c));
模板简介:该模板名称为【如何在没有Guava的情况下,如何将对象列表转换为 Map】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Java】栏目查找您需要的精美模板。