简体   繁体   中英

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

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(_))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM