1

I want to convert an Array[Int] to a Map[Int, Int] where each key is the element of the array and the respective value is the index of the element in the array.

Array(11, 12, 13) => Map((11,0), (12,1), (13,2))

Is it possible to do this without using a Mutable map, with a more functional style?

for example:

myArray.toMap(implicit def (... ))
3
  • 3
    This means, of course, that there will be data loss if your Array has any duplicate values: Array(2,3,2) Commented Oct 22, 2019 at 7:31
  • 1
    @jwvh Nice spot! Corner and worst cases can matter! Commented Oct 22, 2019 at 7:58
  • I will keep this in mind. Thank you! Commented Oct 22, 2019 at 11:47

1 Answer 1

6
scala> Array(11, 12, 13).zipWithIndex.toMap
res0: scala.collection.immutable.Map[Int,Int] = Map(11 -> 0, 12 -> 1, 13 -> 2)

P.S. But use HashMap/HashSet from Scala collections wisely to avoid security vulnerabilities on untrusted input under DoS/DoW attacks that exploit hash collision vulnerabilities of them directly or indirectly through Scala collections methods that use them under hood: toMap, keys, distinct, groupBy, etc..

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.