Java 8 – Stream min() and max() methods

In this article, we will discuss Stream’s min() and max() methods in details with examples

1. Stream min() method :

  • This Stream method is a terminal operation which reads given stream and returns minimum element according to provided Comparator
  • This is the special case of reduction i.e.; Stream.reduce();
  • Method signature :- Optional<T> min(Comparator<? super T> comparator)

2. Stream max() method :

  • This Stream method is a terminal operation which reads given stream and returns maximum element according to provided Comparator
  • This is the special case of reduction i.e.; Stream.reduce();
  • Method signature :- Optional<T> max(Comparator<? super T> comparator)



3. Stream min() and max() methods example :

3.1 To find min and max numbers

  • A list contains integer numbers from 1 to 9
  • We are going to apply min() and max() function to get minimum and maximum number respectively
  • Comparator used:- Comparator.comparing(Integer::valueOf);
package net.bench.resources.stream.min.max.example;

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

public class StreamMinMaxForNumbers {

	public static void main(String[] args) {

		// list of integer numbers
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

		// get minimum number from list of integers
		int minNumber = numbers
				.stream()
				.min(Comparator.comparing(Integer::valueOf))
				.get();

		System.out.println("1. The Minimum number is = " 
				+ minNumber);

		// get maximum number from list of integers
		int maxNumber = numbers
				.stream()
				.max(Comparator.comparing(Integer::valueOf))
				.get();

		System.out.println("2. The Maximum number is = " 
				+ maxNumber);
	}
}

Output:

1. The Minimum number is = 1
2. The Maximum number is = 9

3.2 To find min and max from list of characters

  • A list contains chars values
  • We are going to apply min() and max() function to get minimum and maximum character respectively
  • Note: for comparison it uses ASCII value of the Characters
  • Comparator used:- Comparator.comparing(Character::valueOf);
package net.bench.resources.stream.min.max.example;

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

public class StreamMinMaxForChars {

	public static void main(String[] args) {

		// list of characters
		List<Character> chars = Arrays.asList(
				'a', 'b', 'c', 
				'd', 'e', 'f', 
				'g', 'h', 'i'
				);

		// get minimum char from list of characters
		char minChar = chars
				.stream()
				.min(Comparator.comparing(Character::charValue))
				.get();

		System.out.println("1. The Minimum char is = " 
				+ minChar);

		// get maximum char from list of characters
		char maxChar = chars
				.stream()
				.max(Comparator.comparing(Character::charValue))
				.get();

		System.out.println("2. The Maximum char is = " 
				+ maxChar);
	}
}

Output:

1. The Minimum char is = a
2. The Maximum char is = i

3.3 To find min and max from list of String values

  • A list contains String values
  • We are going to apply min() and max() function to get minimum and maximum String respectively
  • Note: for comparison it uses ASCII value of the String
  • Comparator used:- Comparator.comparing(String::valueOf);
package net.bench.resources.stream.min.max.example;

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

public class StreamMinMaxForStrings {

	public static void main(String[] args) {

		// list of Strings
		List<String> names = Arrays.asList(
				"Putin",
				"Biden",
				"Modi",
				"Ali",
				"Jack"
				);

		// get minimum<string> from list of strings
		String minStr = names
				.stream()
				.min(Comparator.comparing(String::valueOf))
				.get();

		System.out.println("1. The Minimum String is = " + minStr);

		// get maximum<string> from list of strings
		String maxStr = names
				.stream()
				.max(Comparator.comparing(String::valueOf))
				.get();

		System.out.println("2. The Maximum String is = " + maxStr);
	}
}

Output:

1. The Minimum String is = Ali
2. The Maximum String is = Putin

3.4 To find min and max age from list of Students

  • A Student POJO is defined with 3 attributes
  • A list contains 5 Student objects defining their attributes like roll, name, and age
  • We are going to apply min() and max() function to get minimum and maximum Student on the basis of their age
  • Comparator used:- Comparator.comparing(Student::getAge);

Student.java

package net.bench.resources.stream.min.max.example;

public class Student {

	// member variables
	private int rollNumber;
	private String name;
	private int age;

	// constructors
	public Student(int rollId, String name, int age) {
		super();
		this.rollNumber = rollId;
		this.name = name;
		this.age = age;
	}

	// getters & setters
	public int getRollId() {
		return rollNumber;
	}
	public void setRollId(int rollId) {
		this.rollNumber = rollId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

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

StreamMinMaxForStudents.java

package net.bench.resources.stream.min.max.example;

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

public class StreamMinMaxForStudents {

	public static void main(String[] args) {

		// list of students
		List<Student> students = Arrays.asList(
				new Student(1, "Viraj", 17),
				new Student(2, "Krishnanand", 18),
				new Student(3, "Rishi", 16),
				new Student(4, "Suresh", 23),
				new Student(5, "Aditya", 21)
				);

		// get student with minimum age from list of students
		Student studentWithMinAge = students
				.stream()
				.min(Comparator.comparing(Student::getAge))
				.get();

		System.out.println("1. The Student with minimum age is = " 
				+ studentWithMinAge);

		// get student with maximum age from list of students
		Student studentWithMaxAge = students
				.stream()
				.max(Comparator.comparing(Student::getAge))
				.get();

		System.out.println("\n2. The Student with maximum age is = " 
				+ studentWithMaxAge);
	}
}

Output:

1. The Student with minimum age is = Student [rollNumber=3, name=Rishi, age=16]

2. The Student with maximum age is = Student [rollNumber=4, name=Suresh, age=23]

3.5 To find min and max Date

  • A list contains different LocalDate
  • We are going to apply min() and max() function to get minimum and maximum Dates
  • Comparator used:- Comparator.comparing(LocalDate::toEpochDay);
package net.bench.resources.stream.min.max.example;

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

public class StreamMinMaxForDates {

	public static void main(String[] args) {

		// list of LocalDate
		List<LocalDate> localDates = Arrays.asList(
				LocalDate.now(),
				LocalDate.now().plusDays(5),
				LocalDate.now().minusDays(5),
				LocalDate.now().plusMonths(1),
				LocalDate.now().minusMonths(1)
				);

		// get minimum LocalDate
		Optional<LocalDate> minLocalDate = localDates
				.stream()
				.min(Comparator.comparing(LocalDate::toEpochDay));

		// print to console only if present
		minLocalDate.ifPresent(
				date -> System.out.println("1. The Minimum LocalDate is = " 
						+ date));

		// get minimum LocalDate
		Optional<LocalDate> maxLocalDate = localDates
				.stream()
				.max(Comparator.comparing(LocalDate::toEpochDay));

		// print to console only if present
		maxLocalDate.ifPresent(
				date -> System.out.println("2. The Maximum LoclaDate is = " 
						+ date));
	}
}

Output:

1. The Minimum LocalDate is = 2021-07-19
2. The Maximum LoclaDate is = 2021-09-19

References:

Happy Coding !!
Happy Learning !!

Java 8 - Stream skip() and limit() methods
Java 8 - Stream distinct() method with examples