Java 中是否有相当于 Javascript 的“some”的方法?方法?
我有一个集合,我想知道是否至少有一个元素满足某些条件。本质上, some 在 JavaScript 中所做的事情,我想做就收藏了!
I have a collection and I would like to know if at least one element meets some condition. Essentially, what some does in JavaScript, I would like to do on a collection!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从 Java 8 开始,您可以将 Collection 转换为 Stream 并使用 anyMatch 如下例所示。
As of Java 8, you can convert the Collection into a Stream and use anyMatch as in the following example.
查看 Guava 的
Iterables
类及其any()
实现。或多或少与另一个答案中的 Commons Collections 示例相同,但通用化:
Check out Guava's
Iterables
class and itsany()
implementation.More or less the same thing as the Commons Collections example in the other answer, but genericized:
您可以使用
CollectionUtils
来自 Apache commons-collections:其中
even
是谓词:或者在内联版本中:
是的,它丑陋有两个原因:
commons-collections
不支持泛型。另一方面,在像 Scala 这样的现代 JVM 语言中,您可以编写:
You can use
CollectionUtils
from Apache commons-collections:Where
even
is a predicate:Or in an inlined version:
Yes, it is ugly for two reasons:
commons-collections
does not support generics.On the other hand in modern JVM languages like Scala you can write:
Java 没有内置此功能。 Javascript 的
some()
接受函数指针作为参数,这不是 Java 本身支持的。但模拟some( )
在 Java 中使用循环和回调功能的接口。Java doesn't have this feature built-in. Javascript's
some()
accepts a function pointer as an argument, which is not something that's natively supported in Java. But it should be fairly straight forward to emulate the functionality ofsome()
in Java using a loop and and an interface for the callback functionality.