Java 8 Stream Comparators

The Java 8 Stream comparators can be passed to a sort method, similar to collection or array sort, to allow control over the sort order of the stream. Comparator methods can also be used to control the order of certain data structures or to allow for an ordering of collections of objects without a natural ordering.

The Java 8 Stream Comparators listed below are the most widely used stream operations.

sorted() Method

The sorted() comparator method will return a stream consisting of the elements of this stream, sorted according to natural order. The sorted() comparator has two different method signatures.

Stream<T> sorted()
.....
Stream<T> sorted(Comparator<? super T> comparator)


min() Method

The min() comparator method will return the minimum element of this stream according to the provided Comparator.

Optional<T> min(Comparator<? super T> comparator)


max() Method

The max() comparator method will return the maximum element of this stream according to the provided Comparator.

Optional<T> max(Comparator<? super T> comparator)


distinct() Method

The distinct() comparator method will return a stream consisting of the distinct elements of the stream.

Stream<T> distinct()


allMatch() Method

The allMatch() comparator method will return 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.

boolean allMatch(Predicate<? super T> predicate)


anyMatch() Method

The anyMatch() comparator method will return 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.

boolean anyMatch(Predicate<? super T> predicate)


noneMatch() Method

The noneMatch() comparator method will return whether no elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result.

boolean noneMatch(Predicate<? super T> predicate)


Java References:

  1. Java 8 Stream Interface

Add a Comment

Your email address will not be published. Required fields are marked *