Rakshith Rakshith - 3 months ago 13
Scala Question

Using partition method in splitting a sequence

I have a sequence say a which is like

val a:Seq[Any]=Seq("Hai",1,2,"Hello")


Now I want to split this sequence to 2 different sequence
seqString
is with Datatype
String
and
seqInt
is with datatype
Int
.

scala> val partitioned =a.partition(p => p.isInstanceOf[String])


this splits my sequence to 2 sequence which is
Seq("Hai", "Hello")
and
Seq(1,2)
. Now Suppose I want to Operate on the sequence that I have derived if I try

scala>partitioned._2.map(x => x+1)


I am unable to perform this operation as the resultant from partition method returns
Seq[Any]
.

Answer

If you are ok with multiple traversals, try out a collect with a case statement:

scala> val a:Seq[Any]=Seq("Hai",1,2,"Hello")
a: Seq[Any] = List(Hai, 1, 2, Hello)

scala> val partitioned = (a.collect{case x: Int => x}, a.collect{case x: String => x})
partitioned: (Seq[Int], Seq[String]) = (List(1, 2),List(Hai, Hello))

scala> partitioned._1.map(_ * 2)
res1: Seq[Int] = List(2, 4)