IntStream max() method in Java

Java 8Object Oriented ProgrammingProgramming

The IntStream max() method in the Java IntStream class is used to get the maximum element from the stream. It returns an OptionalInt describing the maximum element of this stream, or an empty optional if this stream is empty.

The syntax is as follows

OptionalInt max()

Here, OptionalInt is a container object which may or may not contain an int value.

Create an IntStream and add some elements in the stream

IntStream intStream = IntStream.of(89, 45, 67, 12, 78, 99, 100);

Now, get the maximum element from the stream

OptionalInt res = intStream.max();

The following is an example to implement IntStream max() method in Java. The isPresent() method of the OptionalInt class returns true if the value is present

Example

 Live Demo

import java.util.*;
import java.util.stream.IntStream;
public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.of(89, 45, 67, 12, 78, 99, 100);
      OptionalInt res = intStream.max();
      System.out.println("The maximum element of this stream:");
      if (res.isPresent()) {
         System.out.println(res.getAsInt());
      } else {
         System.out.println("Nothing!");
      }
   }
}

Output

The maximum element of this stream:
100
raja
Published on 28-Mar-2019 12:34:45
Advertisements