Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 the first list (in this case it's 'd'). I know I can do this with a loop, but is there any fancy functional way to do this quickly in one line?

I've been looking at the Scala List API, but could only found union and intersection (which will give me List('a', 'b', 'c', 'd') and List('a', 'b', 'c') respectively)

like image 370
Enrico Susatyo Avatar asked Sep 06 '10 08:09

Enrico Susatyo


People also ask

How do you find the difference between two lists in Scala?

In Scala Stack class , the diff() method is used to find the difference between the two stacks. It deletes elements that are present in one stack from the other one. Return Type: It returns a new stack which consists of elements after the difference between the two stacks.

How do you check if an element is in a list Scala?

contains() function in Scala is used to check if a list contains the specific element sent as a parameter. list. contains() returns true if the list contains that element.

How do you check if a list does not contain an element?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.


2 Answers

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.

like image 115
olle kullberg Avatar answered Sep 20 '22 05:09

olle kullberg


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

like image 39
vodkhang Avatar answered Sep 22 '22 05:09

vodkhang