Java 8 列表<V>进入 Map<K,V>

2022-01-22 00:00:00 lambda java-8 java java-stream

我想使用 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()));

相关文章