4

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.

David Moles
  • 48,006
  • 27
  • 136
  • 235

2 Answers2

5

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.

JuanMoreno
  • 2,498
  • 1
  • 25
  • 34
Nándor Előd Fekete
  • 6,988
  • 1
  • 22
  • 47
1

It seems that there is a toLinkedMap() now. Hope it can help here.

JuanMoreno
  • 2,498
  • 1
  • 25
  • 34
Jerome
  • 131
  • 6