Scala两个列表的区别

时间:2013-04-29 11:58:46

标签: list scala

我有两个清单:

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

我想从list2删除所有list1个元素,即我想要

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

我做了list1 diff list2 这让我List("word2","word2","word3","word1")只删除了第一次出现的“word1”。

我无法将其转换为集合,因为我需要有关重复的知识(请参阅上面的“word2”)。怎么办?

3 个答案:

答案 0 :(得分:59)

你可以

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

删除list2中的所有项目。 (您不需要list2中的重复知识。)

答案 1 :(得分:7)

你可以试试这个:

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

println(list1.filterNot(list2.contains(_)))

答案 2 :(得分:1)

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

这可以做到。