scalaspark-shell

How to convert a list to a list of tuples in scala?


Input: Val l= List("k1","v1","k2","v2")

Desired output:

List(("k1","v1"),("k2","v2"))

I have tried using zip,folding, slicing but no luck.

Note:I have done it in python but couldn't able to do in scala.


Solution

  • I would do this like this:

    List("k1","v1","k2","v2")
      .grouped(2) // groups into a Lists of up to 2 elements
      .collect { case List(a, b) => a -> b } // maps to tuples while dropping possible 1-element list
      .toList // converts from Iterable to List
    

    However, it would be perfectly doable without grouped:

    list.foldLeft(List.empty[(String, String)] -> (None: Option[String])) {
      case ((result, Some(key)), value) =>  (result :+ (key -> value)) -> None
      case ((result, None), key) =>         result -> Some(key)
    }._1
    

    or

    def isEven(i: Int) = i % 2 == 0
    
    val (keys, values) = list.zipWithIndex.partition(p => isEven(p._2))
    
    (key zip values).map { case ((k, _), (v, _)) => k -> v }
    

    Of course if performance was really critical I would implement it in slightly different way to avoid allocations (e.g. by prepending results in foldLeft and reversing final results, or by using tailrec or ListBuffer).