zl程序教程

您现在的位置是:首页 >  后端

当前栏目

一行代码, Java 怎样把List 转成 Map 的方法( Java 8 中的Stream API )

2023-09-14 09:07:21 时间
List<EmployeeJobDTO> subs = getDirectSubordinates(workNo);
// 一行代码, 把List 转成 Map
val subMap = subs.stream().collect(Collectors.toMap(EmployeeJobDTO::getWorkNo, it -> it));

代码解析

public static <T, K, U> Collector<T, ?, Map<K,U>> toMap(
Function<? super T, ? extends K> keyMapper, // Key 映射器
Function<? super T, ? extends U> valueMapper // Value 映射器
) {
        return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
}


public static <T, K, U, M extends Map<K, U>> Collector<T, ?, M> toMap(
Function<? super T, ? extends K> keyMapper,                        
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction,               
Supplier<M> mapSupplier
) {
        BiConsumer<M, T> accumulator
                = (map, element) -> map.merge(keyMapper.apply(element),