Java有类似于JavaScript的“some”方法吗?

21

我有一个集合,想知道是否至少有一个元素满足某个条件。本质上,我想在集合上做的就是 JavaScript 中 some 方法所能实现的功能!

4个回答

23

从Java 8开始,您可以将Collection转换为Stream,并像以下示例中使用anyMatch

import java.util.Arrays;
import java.util.List;

public class SomeExample {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, -6, 7);
        boolean hasNegative = list.stream().anyMatch(x -> x < 0);
        if (hasNegative) {
            System.out.println("List contains some negative number");
        }
        else {
            System.out.println("List does not contain any negative number");
        }
    }
}

18

查看GuavaIterables类和其any()实现。

与其他答案中Commons Collections示例更或多或少相同,但是泛型化了:

List<String> strings = Arrays.asList("ohai", "wat", "fuuuu", "kthxbai");
boolean well = Iterables.any(strings, new Predicate<String>() {
    @Override public boolean apply(@Nullable String s) {
        return s.equalsIgnoreCase("fuuuu");
    }
});
System.out.printf("Do any match? %s%n", well ? "Yep" : "Nope");

4
通用集合类缺乏泛型是Commons Collections的主要缺陷。 - Has QUIT--Anony-Mousse
@Anony-Mousse 是的,这很麻烦,但我仍然在使用它:/ - Dave Newton

4
你可以使用来自Apache commons-collectionsCollectionUtils
List<Integer> primes = Arrays.asList(3, 5, 7, 11, 13)
CollectionUtils.exists(primes, even);  //false

其中even是一个谓词:

Predicate even = new Predicate() {
    public boolean evaluate(Object object) {
        return ((Integer)object) % 2 == 0;
    }
}

或者以内联版本的形式:

List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13)
CollectionUtils.exists(primes, new Predicate() {
    public boolean evaluate(Object object) {
        return ((Integer)object) % 2 == 0;
    }
});

是的,这很丑陋,原因有两个:

  1. Java目前还不支持将函数作为一等公民,而是通过单抽象方法接口来模拟。
  2. commons-collections 不支持泛型。

另一方面,在现代JVM语言(如Scala)中,你可以这样写:

List(3,5,7,11,13,17).exists(_ % 2 == 0)

3
支持这种方法的另一个第三方库是Google Guava,它拥有Iterables.any()方法。 - axtavt
2
Guava 支持泛型。 ;) - Louis Wasserman
Java 8 将拥有 Lambda 表达式。此外,SAM 类现在被称为函数式接口。 - David Conrad
CollectionUtils.exists现在已经被弃用。请尝试使用上面答案中的anyMatch - Jason

0

Java没有内置此功能。Javascript的some()接受函数指针作为参数,这不是Java本地支持的内容。但使用循环和回调功能的接口应该可以相对简单地模拟some()的功能。


它接受一个函数,但这并不等同于一个函数指针。 - xlem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接