Search code examples
listlinkedhashmapvavr

Javaslang / Vavr LinkedHashMap from List


Is there a concise, idiomatic way to create an order-preserving map from a Javaslang / Vavr List? List.toMap() returns a plain HashMap, so that doesn't do it. What I have right now is something like this --

listOfKeys.foldLeft(
    LinkedHashMap.<Key, Value>.empty(), 
    (m, k) -> m.put(k, valueFor(k))
);

-- but this seems more verbose than necessary, and possibly less efficient as well.


Solution

  • The Value.collect method (inherited by List) is usually used for this purpose, which is analogous to the Java 8 Stream's collect method. It takes a collector to perform a mutable reduction (see note). Vavr LinkedHashMap provides a static collector() method, so you can use that to get an instance to a collector which will collect to a LinkedHashMap.

    listOfKeys.map(key -> new Tuple2<>(key, valueForKey(key)))
        .collect(LinkedHashMap.collector());
    

    I'm not sure how it will perform compared to your solution though, I don't think it will have a difference in performance, but as an added bonus it's compatible with the JDK collectors, so you can use that to collect to JDK collections easily.

    * Note that since the Vavr collections are immutable, mutable reduction isn't actually mutable in this context.