我想使用Java8的streams和lambdas将对象列表转换为 map .

这就是我在Java7及以下版本中编写它的方式.

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;
}

我可以使用Java8和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();
        }
    });
}

番石榴和Java8 lambdas.

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

推荐答案

Collectors documentation为基础,简单如下:

Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName,
                                              Function.identity()));

Java相关问答推荐

OpenRewriter-如何替换连锁/流畅方法调用中的方法?

Java中Stream(java.util.stream)和linkedList数据 struct 之间是什么关系?

内容处置 destruct 了PSP请求

将@ManyToOne JPA Composite Key用作Id保存实体添加额外参数

PostgreSQL货币兑换率查询

S的字符串表示是双重精确的吗?

条件加载@ManyToMany JPA

从Spring5迁移到Spring6:无法在雅加达包中找到类

如何在不删除Java中已有内容的情况下覆盖文件内容?

如何使用log4j2(Json)记录由";异常引起的所有";?

在Oracle JDBC连接中,连接失效和身份验证失效是什么意思?

无法播放音频:从资源加载库GStreamer-Lite失败

从映射列表中检索所有键

我如何为我的Java抵押贷款代码执行加薪操作(&Q)

具有多个模式的DateTimeForMatter的LocalDate.parse失败

从12小时开始的日期模式

JavaFX复杂项目体系 struct

Maven-Dependency-Plugin 3.6.+开始查找在依赖关系:分析目标期间找到的新的使用的未声明依赖关系

当我将JTextField的getText函数与相等的String进行比较时;t返回true

java21预览未命名的符号用于try-with-resources