Difference between anyMatch and findAny in java 8

ε祈祈猫儿з 提交于 2021-02-04 03:20:34

问题


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.


回答1:


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.




回答2:


There are more than two ways in Java 8

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

The difference is in the type of the return value:

  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);
    


来源:https://stackoverflow.com/questions/44179756/difference-between-anymatch-and-findany-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!