问题
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:
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");
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");
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;
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);
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