java.util.stream.IntStream in Java 8, deals with primitive ints. It helps to solve the problems like finding maximum value in array, finding minimum value in array, sum of all elements in array, and average of all values in array in a new way. IntStream max() returns an OptionalInt describing the maximum element of this stream, or an empty optional if this stream is empty.
Syntax :
OptionalInt() max()
Where, OptionalInt is a container object which
may or may not contain a int value.
Example 1 :
import java.util.*;
import java.util.stream.IntStream;
class GFG {
public static void main(String[] args)
{
IntStream stream = IntStream.of(- 9 , - 18 , 54 , 8 , 7 , 14 , 3 );
OptionalInt obj = stream.max();
if (obj.isPresent()) {
System.out.println(obj.getAsInt());
}
else {
System.out.println( "-1" );
}
}
}
|
Output :
54
Example 2 :
import java.util.*;
import java.util.stream.IntStream;
class GFG {
public static void main(String[] args)
{
IntStream stream = IntStream.range( 50 , 75 );
int maximum = stream.max().orElse(- 1 );
System.out.println(maximum);
}
}
|
Output :
74
Example 3 :
import java.util.*;
import java.util.stream.IntStream;
class GFG {
public static void main(String[] args)
{
IntStream stream = IntStream.range( 50 , 50 );
int maximum = stream.max().orElse(- 1 );
System.out.println(maximum);
}
}
|
Output :
-1