Find elements in a list that are not in the second list (in scala)

前端 未结 3 1585
既然无缘
既然无缘 2021-02-12 09:32

Suppose I have two lists:

val a = List(\'a\', \'b\', \'c\')
val b = List(\'a\', \'b\', \'c\', \'d\')

I want to get the element which is not in

3条回答
  •  無奈伤痛
    2021-02-12 10:25

    Of course, this can be done in many ways. For flat structures like list of numbers and strings diff is the most elegant. Other ways are,

    val ans1 = for { x <- b  if !a.contains(x) } yield x
    
    val ans2 = for { x <- b if !a.exists(_ == x) } yield x
    
    val ans3 = b filterNot (x => b.contains(x) )
    
    val ans4 = b diff a
    

提交回复
热议问题