I have a List and I need to convert it to the Map but with the same order of keys, so I need to convert to the LinkedHashMap. I need something like that:
list.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
but with concrete type of map, like :
list.stream().collect(Collectors.toCollection(LinkedHashMap::new))
Is it possible to combine both variants above?
Yes, just use the Collectors.toMap
variant that includes a merge function and a map supplier:
<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)
Using a simple merge function (that selects the first value) will look like this:
LinkedHashMap<KeyType,ValueType> map =
list.stream().collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(v1,v2)->v1,
LinkedHashMap::new));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With