There are following way to Find largest number in an array and list in java 8.
Using IntStream.of() method:-
- IntStream.of(int value) returns a sequential ordered stream data whose elements are the specified values.
- syntax:- static IntStream of(int… values)
- Here we call IntStream.of() method to pass array as input data.
- After that call max method to describing the maximum element of this stream.
- Now it return max element inside optionalInt variable i.
- Return type of IntStream of() method is optionalInt.
Using Stream.max() method :-
- Stream.max() method allows to get maximum value from the processing Stream elements.here we pass java.util.Comparator as argument type.
- Inside Integer::compare Comparators as method-reference comparing the each element.
- Stream.max() method returns type is Optional<T>
- 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);
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 :- OptionalInt[78]
largest number from Stream.max() method in list:- 87