public static <T, K, U>
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction) {
return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
}
将指定集合的转变为map
keyMapper:指定key
valueMapper:指定value
相同key会报错
BinaryOperator:处理相同key冲突
- (v1,v2)->v1:取前一个key的value
- (v1,v2)->v2:取后一个key的value
- (v1,v2)->DIY:自定义冲突时的value(比如v1+v2拼接等)
Map<KeyType,ValueType> map = list.stream().collect(Collectors.toMap(key,value,merge));
// 例子
// userList->list
Map<Long,User> map = list.stream().collect(Collectors.toMap(User::getId(),u->u,(v1,v2)->v2));