Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use map and receive an index as well in Scala?

Is there any List/Sequence built-in that behaves like map and provides the element's index as well?

like image 225
Geo Avatar asked Feb 06 '10 13:02

Geo


People also ask

How do you use a map index?

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.

How do you get the index of an element in a list in Scala?

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.

How do you add a value to a map in Scala?

We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.

How do I convert a list to map in Scala?

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.


1 Answers

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) ) 
like image 51
Viktor Klang Avatar answered Oct 19 '22 06:10

Viktor Klang