How to use Collectors.minBy() in Java 8

57 total views, 1 views today

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

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

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

Collectors.minBy() syntax

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

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

Collectors.minBy() example

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

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

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

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

Output

1

References : Collectors.minBy()

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!.

1 thought on “How to use Collectors.minBy() in Java 8

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.