两份名单的斯卡拉差异(Scala difference of two lists)

2019-09-01 09:14发布

我有两个列表:

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")这是只去掉的“字词1”第一次出现。

因为我需要有关重复知识(见上述“单词2”),我不能把它转换成集。 该怎么办?

Answer 1:

您可以

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

去除所有项目list2 。 (你不需要在重复的知识list2 )。



Answer 2:

你可以试试这个:

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

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


文章来源: Scala difference of two lists
标签: list scala