There are multiple ways to find the largest number in an array and a list in Java 8.
Using IntStream.of() method:-
- IntStream.of(int… values) returns a sequential IntStream containing the specified int values.
- syntax:- static IntStream of(int… values)
- Here we call IntStream.of() method to pass array as input data.
- After that, we call the max() method to find the maximum element.
- Now it return max element inside optionalInt variable i.
- The IntStream.of() method returns an IntStream, and the max() method returns an OptionalInt.
Using Stream.max() method :-
- Stream.max() method allows to get maximum value from the processing Stream elements.Here we pass Comparator as an argument type.
- Inside Integer::compare Comparators as method-reference comparing the each element.
- The Stream.max() method returns an Optional<T> containing the maximum element of the stream according to the provided comparator.
- From get() method of Optional<T> we can find maximum number from the List .
- Now print the largest number value.
import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class AS {
public static void main(String[] args) {
int arr[] = { 12,34,56,78,32,67 };
List list = Arrays.asList(32,56,87,45,12);
OptionalInt i = IntStream.of(arr).max();
System.out.println("largest number from IntStream.of() method in array :- " + i.getAsInt());
Integer l = list.stream().max(Integer::compare).get();
System.out.println("largest number from Stream.max() method in list:- " + l);
}
}
Output :-
largest number from IntStream.of() method in array :- 78
largest number from Stream.max() method in list:- 87