Is there any List/Sequence built-in that behaves like map
and provides the element's index as well?
The Map Index pane displays a pivot view that shows your map topics categorized by their markers and elements, providing a fast and easy way to see and navigate to your map's important content. You can use the controls at the top of the pane to view the Markers list or Elements list, and customize the view.
Scala List indexOf() method with example. The indexOf() method is utilized to check the index of the element from the stated list present in the method as argument. Return Type: It returns the index of the element present in the argument.
We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.
To convert a list into a map in Scala, we use the toMap method. We must remember that a map contains a pair of values, i.e., key-value pair, whereas a list contains only single values. So we have two ways to do so: Using the zipWithIndex method to add indices as the keys to the list.
I believe you're looking for zipWithIndex?
scala> val ls = List("Mary", "had", "a", "little", "lamb") scala> ls.zipWithIndex.foreach{ case (e, i) => println(i+" "+e) } 0 Mary 1 had 2 a 3 little 4 lamb
From: http://www.artima.com/forums/flat.jsp?forum=283&thread=243570
You also have variations like:
for((e,i) <- List("Mary", "had", "a", "little", "lamb").zipWithIndex) println(i+" "+e)
or:
List("Mary", "had", "a", "little", "lamb").zipWithIndex.foreach( (t) => println(t._2+" "+t._1) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With