代码之家  ›  专栏  ›  技术社区  ›  Thiyagu

收集器中缺少带有键、值和映射提供者的toMap方法

  •  0
  • Thiyagu  · 技术社区  · 5 年前

    Collectors.toMap 有三种过载变体。

    1.键和值映射器:

    toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
    

    2.扩展1添加合并函数:

    toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction)
    

    3.与地图供应商扩展2:

    toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)
    

    地图供应商

    合并函数

    persons.stream()
            .collect(Collectors.toMap(Person::getId, Function.identity(),
                    (a, b) -> a, 
                    LinkedHashMap::new));
    

    Collectors.collectingAndThen

    persons.stream()
            .collect(Collectors.collectingAndThen(Collectors.toMap(Person::getId, Function.identity()),
                    LinkedHashMap::new));
    

    编辑:

    正如@Holger在评论中指出的,复制到 LinkedHashMap 在使用toMap方法填充映射时,顺序已经更改,因此没有帮助

    0 回复  |  直到 5 年前