How to use Collectors.maxBy() in Java 8

 161 total views,  1 views today

Welcome to Java 8 series. In this tutorial, you will learn about how to use Collectors.maxBy() in Java 8.

If you would like to learn about Java 8 Stream operations.Please check out this link.

Collectors.maxBy() is used in Java 8 streams and it is a very simple operation to identify the max value of the stream of elements. It uses the comparator interface to identify the maximum value.

Collectors.maxBy() syntax

public static <T> Collector<T,?,Optional<T>> maxBy(Comparator<? super T> comparator)

Based on the documentation, returns a Collector that produces the maximal element according to a given Comparator, described as an Optional<T>.

Collectors.maxBy() example

List<Integer> fruits = Arrays.asList(1,2,3,15,6,17,8);

//Option 1
Optional<Integer> max = fruits.stream().collect(Collectors.maxBy(Comparator.comparing(Integer::valueOf)));

//Option 2
Optional<Integer> max = fruits.stream().collect(Collectors.maxBy(Integer::compareTo));

//Option 3
Optional<Integer> max = fruits.stream().collect(Collectors.maxBy((i, j) -> i.compareTo(j)));

 

Output

17

References : Collectors.maxBy()

I hope you like this tutorial. Thanks for reading and Please leave us a comment below!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.