Home > Net >  remove one seq elements from another seq in scala
remove one seq elements from another seq in scala

Time:09-16

Is there any efficient way of removing elements present in Seq one from Seq two

val one = Seq("A", "B")
val two = Seq("A", "B", "C", "E", "F")
val out = two.map {
  for (n <-one){
    _.filterNot(_ == n)
  }
}

expected output Seq("C", "E", "F") , empty or null of one should also be handled But I'm getting error Cannot resolve overloaded method 'map'

can anyone suggest what am doing wrong here ?

CodePudding user response:

This is the simplest way to do this efficiently:

two.filterNot(one.toSet.contains)

This uses contains to see whether an item is in one or not. one is converted to a Set as this implements contains more efficiently that Seq which does a linear search.

  • Related