list - 在列表中查找不在第二个列表中的元素(在scala中)

标签 list scala functional-programming

假设我有两个列表:

val a = List('a', 'b', 'c')
val b = List('a', 'b', 'c', 'd')

我想获取不在第一个列表中的元素(在本例中为“d”)。我知道我可以使用循环来执行此操作,但是是否有任何精美的功能性方法可以在一行中快速执行此操作?

我一直在查看Scala List API,但是只能找到并集和交集(这将给我List('a','b','c','d')和List('a','b ','c')分别)

最佳答案

我认为您可以使用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)

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

关于list - 在列表中查找不在第二个列表中的元素(在scala中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3649951/

相关文章:

java - 如何知道对象列表中出现次数最多的属性?

javascript - "combine"以功能方式在 javascript 中运行?

Scala 在案例类中使用 Wea​​kReference

scala - Scala Breeze 中的矩阵乘法向量

scala - SBT 无法通过代理解决依赖关系

带有下划线的scala传递函数产生一个函数而不是一个值

performance - 函数式编程中的国际象棋编程

python - 如何缩短多个 IF .... IN ... OR 语句?

ruby - Ruby 的停用词列表

performance - 在保持顺序的同时有效地随机抽样列表