Java 8 Listlt;Vgt; into Maplt;K, Vgt;(Java 8 列表lt;Vgt;进入 Maplt;K,Vgt;)
问题描述
我想使用 Java 8 的流和 lambda 将对象列表转换为 Map.
I want to translate a List of objects into a Map using Java 8's streams and lambdas.
这就是我在 Java 7 及更低版本中的编写方式.
This is how I would write it in Java 7 and below.
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 的情况下完成此任务.
I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without 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 lambda 的 Guava.
And Guava with Java 8 lambdas.
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
推荐答案
基于Collectors
文档 很简单:
Based on Collectors
documentation it's as simple as:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName,
Function.identity()));
这篇关于Java 8 列表<V>进入 Map<K,V>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 列表<V>进入 Map<K,V>


基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01