Java 8- Difference between stream.max() and collectors.maxBy()
2 min readJan 16, 2024
Hi,
this is very confusing for us to understand difference between them.
i am just going to exaplin it……….
In Java’s Stream API, both Stream.max
and Collectors.maxBy
are used to find the maximum element of a stream based on a provided comparator. However, they are used in slightly different contexts.
Stream.max
:
- The
Stream.max
operation is a terminal operation on a stream that returns the maximum element of the stream according to the natural order or a specified comparator. - It returns an
Optional<T>
whereT
is the type of the elements in the stream. If the stream is empty, theOptional
will be empty. - Here’s an example using
Stream.max
:
Optional<Integer> maxNumber = Stream.of(1, 2, 3, 4, 5)
.max(Comparator.naturalOrder());
Collectors.maxBy
:
- The
Collectors.maxBy
is a collector that can be used with thecollect
method to find the maximum element in a stream based on a comparator - It takes a comparator and returns a collector that collects the maximum element according to that comparator.
- The result is wrapped in an
Optional
. - Here’s an example using
Collectors.maxBy
:
Optional<Integer> maxNumber = Stream.of(1, 2, 3, 4, 5)
.collect(Collectors.maxBy(Comparator.naturalOrder()));
Difference:
Stream.max
is used directly on the stream to find the maximum element, whileCollectors.maxBy
is typically used when collecting elements into a container, such as aList
, and you want to find the maximum after the collection operation.Stream.max
returns anOptional<T>
directly, whileCollectors.maxBy
returns anOptional<T>
wrapped in anotherOptional
. This is because the result ofCollectors.maxBy
is the maximum element within a container (e.g., a list), and the outerOptional
is empty if the container is empty.
In summary, if you are working directly with a stream and want to find the maximum element, you might use Stream.max
. If you are collecting elements into a container and want to find the maximum after the collection, you might use Collectors.maxBy.
Thanks ,
Happy Learning :)