Java 将对象列表转换为特性映射

Java 将对象列表转换为特性映射,java,java-8,Java,Java 8,我有一个部分类,具有以下一些属性 class Section { private String name; private String code; // respective getters and setters. } 现在我有了一个截面对象列表,我想将该列表转换为名称和代码的映射。 我知道可以按以下常规方式进行 List<Section> sections = getSections(); Map<String, String> nameC

我有一个
部分
类,具有以下一些属性

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());
}
List sections=getSections();
Map nameCodeMap=新的HashMap();
用于(节:节){
nameCodeMap.put(section.getCode(),section.getName());
}

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

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

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

如果没有具有相同getCode()值的
元素:

并返回合并函数的第二个参数:

Map<String, String> map = sections.stream()
                                 .collect(toMap(Section::getCode, Section::getName, (a, b) -> b);
Map Map=sections.stream()
.collect(toMap(Section::getCode,Section::getName,(a,b)->b);

请查找以下这位女士的代码:

List<Section> sections = Arrays.asList(new Section("Pratik", "ABC"),
                                       new Section("Rohit", "XYZ"));

Map<String, String> nameCodeMap = sections.stream().collect(
                                  Collectors.toMap(section -> section.getName(),
                                                   section -> section.getCode()));

nameCodeMap.forEach((k, v) -> System.out.println("Key " + k + " " + "Value " + v));
List sections=Arrays.asList(新节(“Pratik”、“ABC”),
新条款(“Rohit”、“XYZ”);
Map nameCodeMap=sections.stream().collect(
Collectors.toMap(section->section.getName(),
section->section.getCode());
nameCodeMap.forEach((k,v)->System.out.println(“键”+k+“+”值“+v));

如果你有两个相同的名字怎么办?我不介意重写它们。如果我错了,请纠正我,如果同一个键已经存在,HashMap将替换该键,它不会抛出任何
非法状态异常
你对
HashMap
的选择是正确的。但是
toMap
的collect对重复键有不同的规范。哦,我假设它在内部使用
HashMap
,但事实并非如此。如果是这种情况,那么你的第二个答案就是我想要的。你仍然是对的。它在引擎盖下使用
HashMap
。但是收集器的组合器和累加器(实现收集器所需的)断言它不包含重复的密钥。
Map<String, String> map = sections.stream()
                                 .collect(toMap(Section::getCode, Section::getName, (a, b) -> b);
List<Section> sections = Arrays.asList(new Section("Pratik", "ABC"),
                                       new Section("Rohit", "XYZ"));

Map<String, String> nameCodeMap = sections.stream().collect(
                                  Collectors.toMap(section -> section.getName(),
                                                   section -> section.getCode()));

nameCodeMap.forEach((k, v) -> System.out.println("Key " + k + " " + "Value " + v));