Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Filter List[Int] Which Exists in other List of Tuples

Tags:

list

scala

I've a two lists dest (contains:x) and points (x,y)

dest:List[Int] and Points:List[(Int,Int)]

I want to filter elements in the dest, if it exists in points (x==points._1) i

var newl:List[Int] = List()
for(x<-dest) if(!points.filter(_._1==x).isEmpty) newl=newl:+x

I feel like there must be a better concise way with exists but tuple making it complex. So whats the best way to do the above?

like image 676
Dineshkumar Avatar asked Mar 15 '15 04:03

Dineshkumar


1 Answers

Here is a concise way:

val dest= List(1,2,4,5)
val points = List((1,3), (2,3) , (3,4))
val newl = dest.filter{d => points.exists(_._1 == d)} // returns List(1, 2)

The following is even better order of complexity wise:

val dest= List(1,2,4,5)
val points = List((1,3), (2,3) , (3,4))
val xs = points.map{_._1}.toSet
val newl = dest.filter(xs.contains(_))
like image 159
Rahul Avatar answered Sep 23 '22 11:09

Rahul