Core Java

Java 8 Stream – min() & max() Tutorial

Hello. In this tutorial, we will explain the min() and max() methods introduced in java 8.

1. Introduction

Before diving deep into the practice stuff let us understand the min() and max() methods introduced in java8 programming.

  • Stream.min() – Returns the minimum element of the stream according to the provided comparator.
    • Represented by the code syntax – Optional<T> min(Comparator<? super T> comparator)
    • It is a terminal operation that combines the stream elements and returns the final result
    • Returns an optional or an empty optional if the stream is empty
    • Throw the NullPointerException if the smallest element is null
  • Stream.max() – Returns the maximum element of the stream according to the provided comparator.
    • Represented by the code syntax – Optional<T> max(Comparator<? super T> comparator)
    • It is a terminal operation that combines the stream elements and returns the final result
    • Returns an optional or an empty optional if the stream is empty
    • Throw the NullPointerException if the largest element is null
java 8 min

2. Practice

Let us dive into some practice stuff from here and I am assuming that you already have the Java 1.8 or greater installed in your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Find min and max integer

Create a java file in the com.java8 package and add the following code to it.

MinMaxDemo1.java

package com.java8;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/*
 * Stream.min() - Returns the minimum element of this stream according to the provided comparator.
 * Stream.max() - Returns the maximum element of this stream according to the provided comparator.
 */
public class MinMaxDemo1 {
	
	private static void findMinAndMaxForIntegers() {
		System.out.println("---- Min and Max for integer ----");
		
		final List<Integer> integers = Arrays.asList(6, 5, 20, 2, 1);
		// integer comparator
		final Comparator<Integer> comparator = Comparator.comparing(Integer::intValue);
		
		final Optional<Integer> min = integers.stream().min(comparator);
		// handling the sonar issue to perform ifPresent check before fetch
		min.ifPresent(val -> System.out.println("Stream.min():- " + val));
		
		final Optional<Integer> max = integers.stream().max(comparator);
		// handling the sonar issue to perform ifPresent check before fetch
		max.ifPresent(val -> System.out.println("Stream.max():- " + val));
	}
	
	public static void main(String[] args) {
		findMinAndMaxForIntegers();
	}
}

Run the file and if everything goes well the following output will be logged in the IDE console.

Console output

---- Min and Max for integer ----
Stream.min():- 1
Stream.max():- 20

2.2 Find min and max string

Create a java file in the com.java8 package and add the following code to it.

MinMaxDemo2.java

package com.java8;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/*
 * Stream.min() - Returns the minimum element of this stream according to the provided comparator.
 * Stream.max() - Returns the maximum element of this stream according to the provided comparator.
 */
public class MinMaxDemo2 {

	private static void findMinAndMaxForStrings() {
		System.out.println("---- Min and Max for string ----");
		
		final List<String> strings = Arrays.asList("A", "F", "Z", "B", "P");
		// string comparator
		final Comparator<String> comparator = Comparator.comparing(String::valueOf);
		
		final Optional<String> min = strings.stream().min(comparator);
		// handling the sonar issue to perform ifPresent check before fetch
		min.ifPresent(val -> System.out.println("Stream.min():- " + val));
		
		final Optional<String> max = strings.stream().max(comparator);
		// handling the sonar issue to perform ifPresent check before fetch
		max.ifPresent(val -> System.out.println("Stream.max():- " + val));
	}
	
	public static void main(String[] args) {
		findMinAndMaxForStrings();
	}
}

Run the file and if everything goes well the following output will be logged in the IDE console.

Console output

---- Min and Max for string ----
Stream.min():- A
Stream.max():- Z

2.3 Find min and max object

Create a java file in the com.java8 package and add the following code to it.

MinMaxDemo3.java

package com.java8;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/*
 * Stream.min() - Returns the minimum element of this stream according to the provided comparator.
 * Stream.max() - Returns the maximum element of this stream according to the provided comparator.
 */
public class MinMaxDemo3 {

	private static void findMinAndMaxByName(final List<Student> students) {
		System.out.println("\nMin and max student by name");
		// student name comparator
		final Comparator<Student> name = Comparator.comparing(Student::getName);

		final Optional<Student> min = students.stream().min(name);
		// handling the sonar issue to perform ifPresent check before fetch
		min.ifPresent(val -> System.out.println("Stream.min():- " + val.toString()));

		final Optional<Student> max = students.stream().max(name);
		// handling the sonar issue to perform ifPresent check before fetch
		max.ifPresent(val -> System.out.println("Stream.max():- " + val.toString()));
	}

	private static void findMinAndMaxByAge(final List<Student> students) {
		System.out.println("\nMin and max student by age");
		// student age comparator
		final Comparator<Student> age = Comparator.comparing(Student::getAge);

		final Optional<Student> minAge = students.stream().min(age);
		// handling the sonar issue to perform ifPresent check before fetch
		minAge.ifPresent(val -> System.out.println("Stream.min():- " + val.toString()));

		final Optional<Student> maxAge = students.stream().max(age);
		// handling the sonar issue to perform ifPresent check before fetch
		maxAge.ifPresent(val -> System.out.println("Stream.min():- " + val.toString()));
	}

	public static void main(String[] args) {
		System.out.println("---- Min and Max for object ----");
		
		// student list
		final List<Student> students = new ArrayList<>();
		students.add(new Student("John", 41));
		students.add(new Student("Jane", 20));
		students.add(new Student("Adam", 17));
		students.add(new Student("Eve", 3));
		students.add(new Student("Mathew", 10));
		
		findMinAndMaxByName(students);
		findMinAndMaxByAge(students);
	}
}

class Student {
	private final String name;
	private final int age;

	public Student(final String name, final int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
}

Run the file and if everything goes well the following output will be logged in the IDE console.

Console output

---- Min and Max for object ----

Min and max student by name
Stream.min():- Student [name=Adam, age=17]
Stream.max():- Student [name=Mathew, age=10]

Min and max student by age
Stream.min():- Student [name=Eve, age=3]
Stream.min():- Student [name=John, age=41]

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned the min() and max() methods introduced in java8 programming along with the implementation. The min() method helps to determine the smallest element from the given stream on the basis of a comparator. Similarly, the max method helps to determine the largest element from the given stream on the basis of a comparator. You can download the source code from the Downloads section.

4. Download the Eclipse Project

This was a tutorial about the min() and max() methods in java 8.

Download
You can download the full source code of this example here: Java 8 Stream – min() & max() Tutorial

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button