Use Stream API to find maximum and minimum from a list of integers
Stream API provides a way to perform a sequence of operations on a collection. In this step, we will learn how to use Stream API to find the maximum and minimum elements from a list of integers.
Create a list of integers
List<Integer> numbers = Arrays.asList(10, 2, 30, 5, 4, 20);
Find the maximum element of the list using Stream API.
Optional<Integer> maxNum = numbers.stream().max(Integer::compareTo);
System.out.println("Maximum number: " + maxNum.get());
Find the minimum element of the list using Stream API.
Optional<Integer> minNum = numbers.stream().min(Integer::compareTo);
System.out.println("Minimum number: " + minNum.get());
Now, compile and run this code using the following command:
javac ~/project/LambdaExpressions.java && java LambdaExpressions
The output should be:
Maximum number: 30
Minimum number: 2