gpt4 book ai didi

java - 将对象列表转换为属性映射

转载 作者:行者123 更新时间:2023-11-30 06:40:40 25 4
gpt4 key购买 nike

我有一个 Section 类,其中有一些属性如下

class Section {
private String name;
private String code;
// respective getters and setters.
}

现在我有一个部分对象列表,我想将该列表转换为名称和代码的映射。我知道可以按以下常规方式完成。

List<Section> sections = getSections();
Map<String, String> nameCodeMap = new HashMap<>();
for (Section section : sections) {
nameCodeMap.put(section.getCode(), section.getName());
}

我想知道 Java-8 流是否可以实现类似的功能。

最佳答案

不难。只需将 toMap 收集器与对 getter 的适当方法引用一起使用即可:

sections.stream().collect(
Collectors.toMap(Section::getName, Section::getCode)
);

关于java - 将对象列表转换为属性映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57534190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com