3 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
不難。只需將toMap
收集器與對(duì)吸氣劑的適當(dāng)方法引用一起使用:
sections.stream().collect( Collectors.toMap(Section::getName, Section::getCode) );

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果您沒(méi)有具有Section
相同 getCode() 值的元素:
Map<String, String> map = sections.stream() .collect(toMap(Section::getCode, Section::getName);
如果您有Section
具有相同 getCode() 值的元素,則前一個(gè)將引發(fā),IllegalStateException
因?yàn)樗唤邮茉撝怠K阅惚仨毢喜⑺鼈儭?br/>例如,要實(shí)現(xiàn)與您的實(shí)際代碼相同的事情,即覆蓋現(xiàn)有鍵的現(xiàn)有值,請(qǐng)使用此重載:
toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction)
并返回合并函數(shù)的第二個(gè)參數(shù):
Map<String, String> map = sections.stream() .collect(toMap(Section::getCode, Section::getName, (a, b) -> b);

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
請(qǐng)?jiān)谙旅嬲业脚康拇a:
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));
添加回答
舉報(bào)