Java 8清单 <V> 进入地图 <K, V>

岁酱吖の 提交于 2020-08-12 01:55:14

问题:

I want to translate a List of objects into a Map using Java 8's streams and lambdas. 我想使用Java 8的流和lambda将对象列表转换为Map。

This is how I would write it in Java 7 and below. 这就是我在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;
}

I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava. 我可以使用Java 8和Guava轻松完成此操作,但是我想知道如何在没有Guava的情况下执行此操作。

In 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();
        }
    });
}

And Guava with Java 8 lambdas. 带有Java 8 lambda的番石榴。

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}

解决方案:

参考一: https://stackoom.com/question/1NRX5/Java-清单-V-进入地图-K-V
参考二: https://oldbug.net/q/1NRX5/Java-8-List-V-into-Map-K-V
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!