Java 8 List< V>到地图< K,V> [英] Java 8 List<V> into Map<K, V>
本文介绍了Java 8 List< V>到地图< K,V>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用Java 8的流和lambdas将对象列表转换为Map。
I want to translate a List of objects into a Map using Java 8's streams and lambdas.
这就是我在Java 7及以下版本中编写它的方法。 / p>
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轻松完成此任务,但我想知道如何在没有番石榴的情况下做到这一点。
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);
}
推荐答案
基于 收藏家
文档它很简单:
Based on Collectors
documentation it's as simple as:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName,
Function.identity()));
这篇关于Java 8 List< V>到地图< K,V>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文