In  this tutorial, we will see “What is a minBy() method in Java 8 and how we can use it?” minBy java 8

minBy() method in Java 8 with example...!!! Share on X

Collectors minBy() Method

Syntax & Description

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

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

Type Parameters:

<T> the type of the input elements

Parameters:

comparator a Comparator for comparing elements

Returns:

a Collector that produces the minimal value

How to use it – an Example?

/**
 * Using minBy method as name suggest, Find the person with the min age
 * @author Deepak Verma
 *
 */

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class minBy_Collectors_Method_Java8_Example {

	public static void main(String args[]) {

		List<Person> people = Arrays.asList(
				new Person("Yashika", 15),
				new Person("Deepak", 37),
				new Person("Yash", 17),
				new Person("Isha", 32),
				new Person("Gaurangee", 21)
				);

		Person youngestPerson = people.stream()
				.collect(Collectors.minBy(Comparator.comparing(Person::getAge)))
				.orElse(null);

		System.out.println("Youngest Person among the list is: "+youngestPerson.getName());

	}
}

 

Output:

Youngest Person among the list is: Yashika

minBy java 8

In this example, we have a list of Person objects and we want to find the youngest person in the list. We use the minBy method with a Comparator that compares the ages of the persons and returns the person with the lowest age. The minBy method returns an Optional object, so we use the orElse method to get the actual person object or null if the list is empty.

skip method java 8 stream

Java 8 – Collectors minBy() method with Example Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts