Java 8 のストリームとラムダを使用して、オブジェクトのリストをマップに変換したいと考えています。
これは、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();
}
});
}
そして、Java 8 ラムダを使用した Guava。
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
ベストアンサー1
に基づくCollectors
ドキュメンテーションそれは次のように簡単です:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName,
Function.identity()));