Scala/RDD : How to compare a value of tuple with a list of values in the same tuple

255 Views Asked by At

I have data like below

val t=((1,List(1,2,3,4)),(2,List(1,2,3,4)),(3,List(1,2,3,4)),(4,List(1,2,3,4)))

and I want output like :

1--1
2--2
3--3
4--4

Can some body please help me here by using scala or spark core.

2

There are 2 best solutions below

0
On BEST ANSWER

Another way using RDD:

Input:

(1,List(1, 2, 3, 4))
(2,List(1, 2, 3, 4))
(3,List(1, 2, 3, 4))
(4,List(1, 2, 3, 4))

t.map(x => s"""${x._1} -- ${if(x._2.contains(x._1)) x._1}""").collect.foreach(println)  

Output:

1 -- 1
2 -- 2
3 -- 3
4 -- 4  
0
On

Try this:

  val spark = SparkSession.builder()
    .appName("app_name")
    .master("local[2]")
    .getOrCreate()

  import spark.implicits._

  val df = spark.sparkContext.parallelize(Seq((1,List(1,2,3,4)),(2,List(1,2,3,4)),(3,List(1,2,3,4)),(4,List(1,2,3,4))))
  df.map{
    case (id, list) => s"${id}--${list(id - 1)}"
  }.toDF().show()