There is multiple way to find maximum value from a list in java 8.
- First convert Arrays to list using Arrays.asList() method.
- Now get the Stream data from List using arrayList.stream() method.
Using mapToInt() :- this method maps the stream elements into int. then max() method fetches the maximum elements.
Using reduce() :- this method combines elements into a single result. Inside Integer.max() they check if a>b then prints a otherwise b.
Using max(Integer::compareTo) :- Integer::compareTo method compare two integer value and check value is greater than 0. through max() we find maximum value from that integer.
Using max(Comparator.naturalOrder()) :- Comparator.naturalOrder() method sort the elements in ascending order. then max method fetch the maximum value from this order elements.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class MaxValueTest {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 3, 4, 5, 6, 7, 8, 8, 19);
int maxValue1 = list.stream().mapToInt(Integer::intValue).max().getAsInt();
System.out.println("using mapToInt to fetch max value :- " + maxValue1);
int maxValue2 = list.stream().reduce(0, (a, b) -> Integer.max(a, b));
System.out.println("Using reduce to fecth max value :- " + maxValue2);
int maxValue3 = list.stream().max(Integer::compareTo).get();
System.out.println("Using compareTo to fecth max value :- " + maxValue3);
int maxValue4 = list.stream().max(Comparator.naturalOrder()).get();
System.out.println("Using naturalOrder to fetch max value :- " + maxValue4);
}
}
Output :-
using mapToInt to fetch max value :- 19
Using reduce to fecth max value :- 19
Using compareTo to fecth max value :- 19
Using naturalOrder to fetch max value :- 19