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方法填充映射时,顺序已经更改,因此没有帮助