Difference between anyMatch and findAny in java 8

16,622

They do the same job internally, but their return value is different. Stream#anyMatch() returns a boolean while Stream#findAny() returns an object which matches the predicate.

Share:
16,622
Mehraj Malik
Author by

Mehraj Malik

Updated on June 13, 2022

Comments

  • Mehraj Malik
    Mehraj Malik almost 2 years

    I have an Array and want to perform some matching on it's element.

    I came to know that it could be done in two ways in java 8 :

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

    anyMatch :

    Arrays.stream(alphabet).anyMatch("A"::equalsIgnoreCase);
    

    findAny :

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

    As I can understand both are doing the same work. However, I could not found which one to prefer?

    Could someone please make it clear what is the difference between both of them.

  • Jorn Vernee
    Jorn Vernee almost 7 years
    They almost do the same work. anyMatch is a short-circuit operation, but filter will always process the whole stream.
  • Dariusz
    Dariusz almost 7 years
    @JornVernee are you entirely certain of that statement? As far as I remember streams are "lazy", which, for sequential streams, means that after encountering the first matching value in anyMatch it will be returned and the filter will not be processed further.
  • Jorn Vernee
    Jorn Vernee almost 7 years
    Hmm, I suppose you are right. At least it depends on the implementation. I'm going of the documentation here, where only anyMatch explicitly mentions that it's a short-circuit operation.
  • Eugene
    Eugene almost 7 years
    @JornVernee findAny code : if (!stop && predicate.test(t) == matchKind.stopOnPredicateMatches) { stop = true; ... it is short-circuiting.
  • Jorn Vernee
    Jorn Vernee almost 7 years
    @Eugene is that the JDK9 implementation? The findAny I have doesn't accept a predicate
  • Eugene
    Eugene almost 7 years
    @JornVernee that's the third time this week! :( yes, it is jdk-9; that's the default I have. sorry
  • Jorn Vernee
    Jorn Vernee almost 7 years
    @MehrajMalik Well, it's supposed to come out on 2017/07/27 That's not too long from now.
  • Dariusz
    Dariusz almost 7 years
    @JornVernee I checked, take a look at stackoverflow.com/questions/44180155/…
  • Eugene
    Eugene almost 7 years
    @JornVernee you might have some "substance" here. One is implemented via FindOps and the other via MatchOps. It could have been easily done so that match would call find and just return isPresent on the resulting Optional. I just know I will not be able to sleep normally until I understand why...