#
min() & max() methods
This tutorial explains how we can use min()
and max()
methods with Streams in Java.
min()
andmax()
methods terminate the stream and return the MIN or the MAX value from the stream. We are using a default or custom Comparator implementation.
Please take a look at the following example and read carefully the comments. The code is self-explanatory.
This example is created from a simple Spring Boot application created with Spring Initializr. I am using Maven, Java 17, Spring Boot 3.1.0.
From the base application downloaded from Spring Initializr, I updated the main class as below:
DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.*;
import java.util.concurrent.ExecutionException;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ApplicationContext appContext = SpringApplication.run(DemoApplication.class, args);
Integer[] numbers = {10, 20, 30};
Integer max = Arrays.stream(numbers)
// Get the MAX value from a stream
.max(Comparator.comparing(Integer::valueOf)).get();
System.out.println("MAX="+max);
System.out.println("----------------------------");
Integer min = Arrays.stream(numbers)
// Get the MIN value from a stream
.min(Comparator.comparing(Integer::valueOf)).get();
System.out.println("MIN="+min);
System.out.println("----------------------------");
}
}
min()
andmax()
methods return an Optional variable, for this reason we need to addget()
method to get the value from the Optional class.- instead min(), max() we can use reduce() (for instance :
.reduce(Integer::min).get()
). get() method is used for taken a value from an Optional variable.
When I run this code I receive:
MAX=30
----------------------------
MIN=10
----------------------------
When we are working with Streams, we can have:
- INTERMEDIATE operations:
filter
,map
,limit
,sorted
,peak
,distinct
,skip
,flatMap
- TERMINAL operations:
forEach
,count
,sum
,min
,collect
,reduce
,anyMatch
,noneMatch
,allMatch