如何检查数组是否包含 Scala 2.8 中的特定值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3877863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:28:29  来源:igfitidea点击:

How to check that an array contains a particular value in Scala 2.8?

arraysscala

提问by Ivan

I've got an array A of D unique (int, int) tuples.

我有一个由 D 个唯一 (int, int) 元组组成的数组 A。

I need to know if the array contains (X, Y) value.

我需要知道数组是否包含 (X, Y) 值。

Am I to implement a search algorithm myself or there is a standard function for this in Scala 2.8? I've looked at documentationbut couldn't find anything of such there.

我是自己实现搜索算法还是在 Scala 2.8 中有一个标准函数?我查看了文档,但在那里找不到任何此类内容。

回答by huynhjl

That seems easy (unless I'm missing something):

这似乎很容易(除非我遗漏了什么):

scala> val A = Array((1,2),(3,4))
A: Array[(Int, Int)] = Array((1,2), (3,4))

scala> A contains (1,2)
res0: Boolean = true

scala> A contains (5,6)
res1: Boolean = false

I think the api calls you're looking for is in ArrayLike.

我认为您正在寻找的 api 调用在ArrayLike 中

回答by Suganthan Madhavan Pillai

I found this nice way of doing

我发现了这种很好的做事方式

scala> var personArray = Array(("Alice", 1), ("Bob", 2), ("Carol", 3))
personArray: Array[(String, Int)] = Array((Alice,1), (Bob,2), (Carol,3))

scala> personArray.find(_ == ("Alice", 1))
res25: Option[(String, Int)] = Some((Alice,1))

scala> personArray.find(_ == ("Alic", 1))
res26: Option[(String, Int)] = None

scala> personArray.find(_ == ("Alic", 1)).getOrElse(("David", 1))
res27: (String, Int) = (David,1)