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

前端 未结 3 1578
既然无缘
既然无缘 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:21

    You can use diff for this:

    scala> b diff a
    res1: List[Char] = List(d)
    

    You probably want to work with Set if you are doing diff.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-12 10:32

    I think you can use b -- a. Here is the documentation from scala:

    def -- [B >: A] (that: List[B]) : List[B]
    Computes the difference between this list and the given list that.
    that
    the list of elements to remove from this list.
    returns this list without the elements of the given list that.
    deprecated: use list1 filterNot (list2 contains) instead
    

    Sorry for the deprecated method, here is the current good one: list1 filterNot (list2 contains)

    def filterNot (p: (A) ⇒ Boolean) :

    List[A] Selects all elements of this list which do not satisfy a predicate. p the predicate used to test elements. returns a new list consisting of all elements of this list that do not satisfy the given predicate p. The order of the elements is preserved. definition classes: TraversableLike

    0 讨论(0)
提交回复
热议问题