Javaslang / Vavr LinkedHashMap from list
Is there a concise, idiomatic way to create an order-preserving map from Javaslang / Vavr List
? List.toMap()
returns plain HashMap
, so it doesn't. What I have now is something like this -
listOfKeys.foldLeft(
LinkedHashMap.<Key, Value>.empty(),
(m, k) -> m.put(k, valueFor(k))
);
- but it seems more verbose than necessary, and possibly less efficient.
source to share
Method Value.collect
(inherited List
) is commonly used for this purpose, which is similar to Java 8 Stream collect
. A collector is required to perform volatile pruning (see Note). Vavr LinkedHashMap
provides a static collector()
method, so you can use that to get an instance of the collector to be collected into LinkedHashMap
.
listOfKeys.map(key -> new Tuple2<>(key, valueForKey(key)))
.collect(LinkedHashMap.collector());
I'm not sure how it will perform versus your solution, but I don't think it will make a difference in performance, but as an added bonus, it is compatible with JDK collectors, so you can use it to collect for JDK collections.
* Note that since Vavr collections are immutable, mutable reduction is not really mutable in this context.
source to share