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?
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(_))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With