0

Let's consider the following code:

Set(1, 2, 3, 4, 5)
  .map(k => (k, if (k % 2 == 0) "even" else "odd"))
  .toMap

Is there a way to simplify this in Scala, avoiding the creation of the intermediate set? I'll be doing something performance-sensitive on big collections and it wouldn't hurt to get the Map created on-the-spot instead.

If nothing better comes along, I was thinking of ending up implementing something like this:

Map.from(S, k => if (k % 2 == 0) "even" else "odd"))

I'm still using Scala 2.12.

Thanks

devoured elysium
  • 101,373
  • 131
  • 340
  • 557

1 Answers1

3

You can use foldleft :

(1 to 5).foldLeft(Map.empty[Int, String])(
  (r, k) => r + (k -> (if (k % 2 == 0) "even" else "odd"))
)

Edit

Or, to avoid intermediate collection in toMap approach, you can use view :

(1 to 5).view
  .map(k => (k, if (k % 2 == 0) "even" else "odd"))
  .toMap

Scala: How to create a Map[K,V] from a Set[K] and a function from K to V?

Community
  • 1
  • 1
Rafaël
  • 977
  • 8
  • 17