reduce() to find min and max
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class MaxMinReduceFlight {
public static void main(String[] args) {
List<Integer> nums = Arrays.asList(11,2,3,4,5,6,7);
int max = nums.stream().reduce(0,Integer::max);
Optional<Integer> resultMin = nums.stream().reduce(Integer::min);
System.out.println("max="+max);
System.out.println("min="+resultMin.get());
}
}
Output:
max=11
min=2
Explanation:
Integer::max: This method reference will be used to find max value.
Integer::min: This method reference will be used to find min value.
for finding minimum value we have taken Optional to get the result because if we will take initial value 0 then it will give us 0 as a resulted minimum value.