Java 8 列表<V>进入 Map<K,V> [英] Java 8 List<V> into Map<K, V>

查看:24
本文介绍了Java 8 列表<V>进入 Map<K,V>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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 列表&lt;V&gt;进入 Map&lt;K,V&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆