What is the best way to convert a List[String, Int]
A to List[Int, String]
B. I wanted to use the map function which would iterate through all items in my list A and then return a new list B however whenever I apply the map function on the list A it complains about wrong number of arguments
val listA:List[(String, Int)] = List(("graduates", 20), ("teachers", 10), ("students", 300))
val listB:List[(Int, String)] = listA.map((x:String, y:Int) => y, x)
Any suggestions? Thanks
In Scala, you can convert a list to a map in Scala using the toMap method. A map contains a set of values i.e. key-> value but a list contains single values. So, while converting a list to map we have two ways, Add index to list.
Accessing the elements The individual elements are named _1 , _2 , and so forth. One way of accessing tuple elements is their positions. The individual elements are accessed with tuple(0) , tuple(1) , and so forth.
One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.
Every collection object has the map() method. map() takes some function as a parameter. map() applies the function to every element of the source collection. map() returns a new collection of the same type as the source collection.
How about this:
val listB = listA.map(_.swap)
You need to use pattern matching to get the elements of a pair. I swear a question like this was asked just a few days ago....
listA.map{case (a,b) => (b,a)}
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