EN
Java 8 - find max and min value in a List
0
points
In this article, we would like to show you how to find max and min values in a List in Java 8.
Quick solution
Max value:
List<Integer> integers = Arrays.asList(2, 3, 1);
int max = integers
.stream()
.mapToInt(x -> x)
.max()
.orElseThrow(NoSuchElementException::new);
System.out.println(max); // 3
Min value:
List<Integer> integers = Arrays.asList(2, 3, 1);
int min = integers
.stream()
.mapToInt(x -> x)
.min()
.orElseThrow(NoSuchElementException::new);
System.out.println(min); // 1
1. Maximum
In this example, we use stream.max() method to find the maximum value of integers List.
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
public class Example {
public static void main(String[] args) throws IOException {
List<Integer> integers = Arrays.asList(2, 3, 1);
int max = integers
.stream()
.mapToInt(x -> x)
.max()
.orElseThrow(NoSuchElementException::new);
System.out.println("Max value = " + max); // 3
}
}
Output:
Max value = 3
2. Minimum
In this example, we use stream.min() method to find the minimum value of integers List.
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
public class Example {
public static void main(String[] args) throws IOException {
List<Integer> integers = Arrays.asList(2, 3, 1);
int min = integers
.stream()
.mapToInt(x -> x)
.min()
.orElseThrow(NoSuchElementException::new);
System.out.println("Min value = " + min); // 1
}
}
Output:
Min value = 1