在Scala中查找不在第二个列表中的元素(查找列表差异)

23
假设我有两个列表:
val a = List('a', 'b', 'c')
val b = List('a', 'b', 'c', 'd')
我想获取不在第一个列表中的元素(在这种情况下为'd')。我知道可以用循环来实现,但是否有任何花哨的函数式方法可以在一行内快速实现呢?
我一直在查看Scala List API,但只找到了union和intersection(分别给出List('a', 'b','c','d')和List('a', 'b','c'))。
3个回答

24

你可以使用diff来完成这个任务:

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

如果你在进行差分操作,那么你可能需要使用 Set


15

我认为您可以使用b -- a。这是来自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

很抱歉,这个方法已经被弃用了,这是当前好的方法:list1 filterNot (list2 contains)


1
谢谢,这可行!除了在2.8中,显然他们说它已被弃用并将逐步淘汰:OutputTree.scala:136: 类List中的方法--已被弃用:改用list1 filterNot(list2 contains) - Enrico Susatyo
2
啊,你甚至连弃用注释都复制粘贴了!我的错!=) - Enrico Susatyo
不用担心,我并不真的看到那个过时的行,只是复制整个代码:) - vodkhang

0
当然,这可以用许多方式来完成。对于像数字和字符串列表这样的平面结构,diff 是最优雅的方法。其他方式有,
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接