zipWithIndex() Example

ZipWithIndex() assigns and index to each element in array converting all the elements into a tuple of (element, index)

Example : Filter Header from Header+Data
scala> class Header(myHeader: Array[String])  {
     |   val temp = myHeader.zipWithIndex
     |   temp.foreach(println)
     |   val index = temp.toMap
     |   println(s"index -> $index")
     |   def apply(someHeader: Array[String], key:String):String = {
     |      someHeader(index(key)) 
     |   }
     | }
defined class Header

scala> val myString = "user,product,review"
myString: String = user,product,review

scala> val myList = myString.split(",")
myList: Array[String] = Array(user, product, review)

scala> val myHeader = new Header(myList)
(user,0)
(product,1)
(review,2)
index -> Map(user -> 0, product -> 1, review -> 2)
myHeader: Header = Header@2afb775a

scala> val someData = List("user,product,review", "user1,toy1,rating1", 
     |                               "user2,toy2,rating3")
someData: List[String] = List(user,product,review, user1,toy1,rating1, user2,toy2,rating3)

scala> val mapped = someData.map{ x =>
     |   val splitted = x.split(",")
     |   splitted
     | }
mapped: List[Array[String]] = List(Array(user, product, review), Array(user1, toy1, rating1), Array(user2, toy2, rating3))

scala> val dataOnly = mapped.filter { x =>
     |   myHeader(x, "user") != "user"
     | }
dataOnly: List[Array[String]] = List(Array(user1, toy1, rating1), Array(user2, toy2, rating3))
c116 > a12

No comments:

Post a Comment