3 回答

TA贡献1828条经验 获得超3个赞
不难。只需将toMap
收集器与对吸气剂的适当方法引用一起使用:
sections.stream().collect( Collectors.toMap(Section::getName, Section::getCode) );

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

TA贡献1794条经验 获得超8个赞
请在下面找到女士的代码:
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));
添加回答
举报