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() 值的元素,則前一個將引發(fā),IllegalStateException
因為它不接受該值。所以你必須合并它們。
例如,要實現(xiàn)與您的實際代碼相同的事情,即覆蓋現(xiàn)有鍵的現(xiàn)有值,請使用此重載:
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));
添加回答
舉報