Java 8中anyMatch和findAny的区别

15

我有一个 Array,想对它的元素执行一些匹配操作。

我了解到在 java 8 中可以通过两种方式实现:

String[] alphabet = new String[]{"A", "B", "C"};

anyMatch:

该方法用于判断流中是否存在满足给定条件的元素,如果至少有一个元素满足条件,则返回true,否则返回false。
Arrays.stream(alphabet).anyMatch("A"::equalsIgnoreCase);

findAny:

Arrays.stream(alphabet).filter("a"::equalsIgnoreCase)
        .findAny().orElse("No match found"));

我理解两者都在做同样的工作。然而,我找不到哪一个更好?

请问有人可以澄清一下它们之间的区别吗。

2个回答

40

它们在内部执行相同的工作,但是它们的返回值是不同的。Stream#anyMatch()返回一个boolean,而Stream#findAny()返回与谓词匹配的对象。


11
它们几乎做着相同的工作。anyMatch是一个短路操作,但是filter将始终处理整个流。 - Jorn Vernee
6
@JornVernee 寻找任意代码:if (!stop && predicate.test(t) == matchKind.stopOnPredicateMatches) { stop = true; ... 其中采用了短路计算。 - Eugene
2
@JornVernee 这是本周第三次了!:( 是的,它是jdk-9;这是我默认的版本。抱歉。 - Eugene
2
@MehrajMalik 嗯,它应该在2017/07/27发布,距离现在不算太久。 - Jorn Vernee
2
@JornVernee,你可能在这里有一些“实质性”的东西。其中一个是通过FindOps实现的,另一个是通过MatchOps实现的。本来可以很容易地这样做,即match调用find,并在结果的Optional上返回isPresent。我只是知道在理解原因之前,我将无法正常入睡... - Eugene
显示剩余5条评论

4

Java 8中有不止两种方法

String[] alphabet = new String[]{"A", "B", "C"};

区别在于返回值的类型:

  1. Stream#findAny():

    Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.

    String result1 = Arrays.stream(alphabet)
            .filter("a"::equalsIgnoreCase)
            .findAny()
            .orElse("none match");
    
  2. Stream#findFirst()

    Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.

    String result2 = Arrays.stream(alphabet)
            .filter("a"::equalsIgnoreCase)
            .findFirst()
            .orElse("none match");
    
  3. Stream#count()

    Returns the count of elements in this stream. This is a special case of a reduction and is equivalent to:

    return mapToLong(e -> 1L).sum();
    
    boolean result3 = Arrays.stream(alphabet)
            .filter("a"::equalsIgnoreCase)
            .count() > 0;
    
  4. Stream#anyMatch(Predicate)

    Returns whether any elements of this stream match the provided Predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated.

    boolean result4 = Arrays.stream(alphabet)
            .anyMatch("a"::equalsIgnoreCase);
    
  5. Stream#allMatch(Predicate)

    Returns whether all elements of this stream match the provided Predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated.

    boolean result5 = Arrays.stream(alphabet)
            .allMatch("a"::equalsIgnoreCase);
    

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