【问题标题】:Convert List of Map.Entry to LinkedHashMap将 Map.Entry 列表转换为 LinkedHashMap
【发布时间】:2018-12-13 16:08:48
【问题描述】:

我有一个 List,我需要将其转换为 Map,但键的顺序相同,因此我需要转换为 LinkedHashMap。我需要这样的东西:

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

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

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

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

【问题讨论】:

    标签: java stream java-stream


    【解决方案1】:

    是的,只需使用包含合并功能和地图供应商的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));
    

    【讨论】:

    • 但是不要使用(v1,v2)-&gt;v1,最好使用(v1,v2) -&gt; { throw new AssertionError("keys should already be unique"); }
    【解决方案2】:

    Streams collect 方法有一个签名,允许您传递集合供应商、累加器和组合器。

        <R> R collect(Supplier<R> supplier,
                      BiConsumer<R, ? super T> accumulator,
                      BiConsumer<R, R> combiner);
    

    在这种情况下,您可以将其与

    一起使用
    Map existing; // keys match list values.
    list.stream.collect(
        Maps::newLinkedHashMap,
        (map, item) -> map.put(item, existing.get(item),
        (l, r) -> { throw new IllegalStateException("combiner not needed here");}
    );
    

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      • 2013-03-04
      相关资源
      最近更新 更多