Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List of Map.Entry to LinkedHashMap

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?

like image 797
Fairy Avatar asked Dec 14 '22 15:12

Fairy


1 Answers

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));
like image 140
Eran Avatar answered Dec 16 '22 07:12

Eran