Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - How to convert from List of tuples of type (A,B) to type (B,A) using map

Tags:

scala

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

like image 305
cdugga Avatar asked Oct 18 '12 20:10

cdugga


People also ask

How do I convert a list to map in Scala?

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.

How to access elements of tuple in Scala?

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.

What is the difference between list and tuple in Scala?

One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.

How do I use the map function in Scala?

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.


2 Answers

How about this:

val listB = listA.map(_.swap)
like image 190
Jean-Philippe Pellet Avatar answered Nov 15 '22 10:11

Jean-Philippe Pellet


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)}
like image 30
Kim Stebel Avatar answered Nov 15 '22 11:11

Kim Stebel