在列表中查找不在第二个列表中的元素(在scala中) [英] Find elements in a list that are not in the second list (in scala)

查看:71
本文介绍了在列表中查找不在第二个列表中的元素(在scala中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个列表:

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

我想获取不在第一个列表中的元素(在本例中为'd').我知道我可以用一个循环来做到这一点,但是有没有一种花哨的功能性方法可以在一行中快速地做到这一点?

I want to get the element which is not in the first list (in this case it's 'd'). I know I can do this with a loop, but is there any fancy functional way to do this quickly in one line?

我一直在查看Scala List API,但只能找到并集和交集(这将为我提供List('a','b','c','d')和List('a' ,"b","c"))

I've been looking at the Scala List API, but could only found union and intersection (which will give me List('a', 'b', 'c', 'd') and List('a', 'b', 'c') respectively)

推荐答案

我认为您可以使用b -- a.这是来自scala的文档:

I think you can use b -- a. Here is the documentation from 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)

Sorry for the deprecated method, here is the current good one: list1 filterNot (list2 contains)

def filterNot (p: (A) ⇒ Boolean) :

列表[A]选择此元素的所有元素 不满足谓词的列表. p用于测试元素的谓词. 返回一个包含所有内容的新列表 此列表中不包含的元素 满足给定的谓词p.这 元素的顺序被保留. 定义类:TraversableLike

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

这篇关于在列表中查找不在第二个列表中的元素(在scala中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆