首页 > 解决方案 > 将 Map.Entry 列表转换为 LinkedHashMap

问题描述

我有一个列表,我需要将它转换为 Map,但键的顺序相同,所以我需要转换为 LinkedHashMap。我需要这样的东西:

list.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

但使用具体类型的地图,例如:

list.stream().collect(Collectors.toCollection(LinkedHashMap::new))

是否可以结合上述两种变体?

标签: javastreamjava-stream

解决方案


是的,只需使用Collectors.toMap包含合并功能和地图供应商的变体:

<T, K, U, M extends Map<K, U>> Collector<T, ?, M> java.util.stream.Collectors.toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)

使用简单的合并函数(选择第一个值)将如下所示:

LinkedHashMap<KeyType,ValueType> map =
    list.stream().collect(Collectors.toMap(Map.Entry::getKey, 
                                           Map.Entry::getValue,
                                           (v1,v2)->v1,
                                           LinkedHashMap::new));

推荐阅读