在 Scala 中查找与谓词匹配的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9556579/
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
Finding an item that matches predicate in Scala
提问by Jeff Storey
I'm trying to search a scala collection for an item in a list that matches some predicate. I don't necessarily need the return value, just testing if the list contains it.
我正在尝试在 Scala 集合中搜索与某个谓词匹配的列表中的项目。我不一定需要返回值,只是测试列表是否包含它。
In Java, I might do something like:
在 Java 中,我可能会执行以下操作:
for ( Object item : collection ) {
if ( condition1(item) && condition2(item) ) {
return true;
}
}
return false;
In Groovy, I can do something like:
在 Groovy 中,我可以执行以下操作:
return collection.find { condition1(it) && condition2(it) } != null
What's the idiomatic way to do this in Scala? I could of course convert the Java loop style to Scala, but I feel like there's a more functional way to do this.
在 Scala 中这样做的惯用方法是什么?我当然可以将 Java 循环样式转换为 Scala,但我觉得有一种更实用的方法可以做到这一点。
回答by om-nom-nom
Use filter:
使用过滤器:
scala> val collection = List(1,2,3,4,5)
collection: List[Int] = List(1, 2, 3, 4, 5)
// take only that values that both are even and greater than 3
scala> collection.filter(x => (x % 2 == 0) && (x > 3))
res1: List[Int] = List(4)
// you can return this in order to check that there such values
scala> res1.isEmpty
res2: Boolean = false
// now query for elements that definitely not in collection
scala> collection.filter(x => (x % 2 == 0) && (x > 5))
res3: List[Int] = List()
scala> res3.isEmpty
res4: Boolean = true
But if all you need is to check use exists:
但是,如果您只需要检查使用exists:
scala> collection.exists( x => x % 2 == 0 )
res6: Boolean = true
回答by Paolo Falabella
Testing if value matching predicate exists
测试值匹配谓词是否存在
If you're just interested in testing if a value exists, you can do it with.... exists
如果您只是对测试值是否存在感兴趣,则可以使用.... exists
scala> val l=(1 to 4) toList
l: List[Int] = List(1, 2, 3, 4)
scala> l exists (_>5)
res1: Boolean = false
scala> l exists (_<2)
res2: Boolean = true
scala> l exists (a => a<2 || a>5)
res3: Boolean = true
Other methods (some based on comments):
其他方法(一些基于评论):
Counting matching elements
计算匹配元素
Count elements that satisfy predicate (and check if count > 0)
计算满足谓词的元素(并检查是否计数 > 0)
scala> (l count (_ < 3)) > 0
res4: Boolean = true
Returning first matching element
返回第一个匹配元素
Find the first element that satisfies predicate (as suggested by Tomer Gabel and Luigi Plinge this should be more efficient because it returns as soon as it finds one element that satisfies the predicate, rather than traversing the whole List anyway)
找到满足谓词的第一个元素(正如 Tomer Gabel 和 Luigi Plinge 所建议的那样,这应该更有效,因为它会在找到满足谓词的元素后立即返回,而不是遍历整个 List)
scala> l find (_ < 3)
res5: Option[Int] = Some(1)
// also see if we found some element by
// checking if the returned Option has a value in it
scala> l.find(_ < 3) isDefined
res6: Boolean = true
Testing if exact value exists
测试是否存在精确值
For the simple case where we're actually only checking if one specific element is in the list
对于我们实际上只检查一个特定元素是否在列表中的简单情况
scala> l contains 2
res7: Boolean = true
回答by senjin.hajrulahovic
The scala way would be to use exists:
Scala 的方法是使用exists:
collection.exists(item => condition1(item) && condition2(item))
And since java 8 you can use anyMatch:
从 Java 8 开始,您可以使用anyMatch:
collection.stream().anyMatch(item -> condition1(item) && condition2(item));
which is much better than a plain for or foreach.
这比普通的 for 或 foreach 好得多。
回答by Yuva Yuvi
Filter and exists keywords to get the matching values from Lists
过滤并存在关键字以从列表中获取匹配的值
val values = List(1,2,3,4,5,6,7,8,9,10,....,1000) //List -1
val factors= List(5,7) // List -2
//To get the factors of List-2 from List-1
values .filter(a => factors.exists(b => a%b == 0)) //Apply different logic for our convenience
Given code helps to get the matching values from 2 different lists
给定的代码有助于从 2 个不同的列表中获取匹配值

