Java 8- Difference between stream.max() and collectors.maxBy()

A cup of JAVA coffee with NeeSri
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> where T is the type of the elements in the stream. If the stream is empty, the Optional 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 the collect 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, while Collectors.maxBy is typically used when collecting elements into a container, such as a List, and you want to find the maximum after the collection operation.
  • Stream.max returns an Optional<T> directly, while Collectors.maxBy returns an Optional<T> wrapped in another Optional. This is because the result of Collectors.maxBy is the maximum element within a container (e.g., a list), and the outer Optional 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 :)

--

--

No responses yet