Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the difference between two lists?

Tags:

list

scala

I have two lists:

val list1 = List("word1","word2","word2","word3","word1")
val list2 = List("word1","word4")

I want to remove all occurrences of list2 elements from list1, i.e. I want

List("word2","word2","word3") <= list1 *minus* list2

I did list1 diff list2 which gives me List("word2","word2","word3","word1") which is removing only the first occurrence of "word1".

I cannot convert it to sets because I need knowledge about duplicates (see "word2" above). What to do?

like image 573
Pavan K Mutt Avatar asked Apr 29 '13 11:04

Pavan K Mutt


3 Answers

You can use

val unwanted = list2.toSet
list1.filterNot(unwanted)

to remove all items in list2 (you don't need knowledge of duplicates in list2).

like image 178
Rex Kerr Avatar answered Oct 16 '22 23:10

Rex Kerr


val list1 = List("word1","word2","word2","word3","word1")
val list2 = List("word1","word4") 
list1 diff list2

This will do it.

like image 37
Kuang Liang Avatar answered Oct 17 '22 00:10

Kuang Liang


You could try this:

val list1 = List("word1","word2","word2","word3","word1")
val list2 = List("word1","word4")

println(list1.filterNot(list2.contains(_)))
like image 9
cmbaxter Avatar answered Oct 16 '22 22:10

cmbaxter