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

我有一个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 流是否可以实现类似的功能。


繁花如伊
浏览 137回答 3
3回答

倚天杖

不难。只需将toMap收集器与对吸气剂的适当方法引用一起使用:sections.stream().collect( &nbsp;&nbsp;&nbsp;&nbsp;Collectors.toMap(Section::getName,&nbsp;Section::getCode) );

汪汪一只猫

如果您没有具有Section相同 getCode() 值的元素:Map<String,&nbsp;String>&nbsp;map&nbsp;=&nbsp;sections.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(toMap(Section::getCode,&nbsp;Section::getName);如果您有Section具有相同 getCode() 值的元素,则前一个将引发,IllegalStateException因为它不接受该值。所以你必须合并它们。例如,要实现与您的实际代码相同的事情,即覆盖现有键的现有值,请使用此重载:toMap(Function<?&nbsp;super&nbsp;T,&nbsp;?&nbsp;extends&nbsp;K>&nbsp;keyMapper, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Function<?&nbsp;super&nbsp;T,&nbsp;?&nbsp;extends&nbsp;U>&nbsp;valueMapper, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;BinaryOperator<U>&nbsp;mergeFunction)并返回合并函数的第二个参数:Map<String,&nbsp;String>&nbsp;map&nbsp;=&nbsp;sections.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(toMap(Section::getCode,&nbsp;Section::getName,&nbsp;(a,&nbsp;b)&nbsp;->&nbsp;b);

幕布斯7119047

请在下面找到女士的代码:List<Section> sections = Arrays.asList(new Section("Pratik", "ABC"),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;new Section("Rohit", "XYZ"));Map<String, String> nameCodeMap = sections.stream().collect(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Collectors.toMap(section -> section.getName(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;section -> section.getCode()));nameCodeMap.forEach((k, v) -> System.out.println("Key " + k + " " + "Value " + v));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java