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.
Max value:
xxxxxxxxxx
1
List<Integer> integers = Arrays.asList(2, 3, 1);
2
3
int max = integers
4
.stream()
5
.mapToInt(x -> x)
6
.max()
7
.orElseThrow(NoSuchElementException::new);
8
9
System.out.println(max); // 3
Min value:
xxxxxxxxxx
1
List<Integer> integers = Arrays.asList(2, 3, 1);
2
3
int min = integers
4
.stream()
5
.mapToInt(x -> x)
6
.min()
7
.orElseThrow(NoSuchElementException::new);
8
9
System.out.println(min); // 1
In this example, we use stream.max()
method to find the maximum value of integers
List.
xxxxxxxxxx
1
import java.io.IOException;
2
import java.util.Arrays;
3
import java.util.List;
4
import java.util.NoSuchElementException;
5
6
7
public class Example {
8
9
public static void main(String[] args) throws IOException {
10
11
List<Integer> integers = Arrays.asList(2, 3, 1);
12
13
int max = integers
14
.stream()
15
.mapToInt(x -> x)
16
.max()
17
.orElseThrow(NoSuchElementException::new);
18
19
System.out.println("Max value = " + max); // 3
20
}
21
}
Output:
xxxxxxxxxx
1
Max value = 3
In this example, we use stream.min()
method to find the minimum value of integers
List.
xxxxxxxxxx
1
import java.io.IOException;
2
import java.util.Arrays;
3
import java.util.List;
4
import java.util.NoSuchElementException;
5
6
7
public class Example {
8
9
public static void main(String[] args) throws IOException {
10
11
List<Integer> integers = Arrays.asList(2, 3, 1);
12
13
int min = integers
14
.stream()
15
.mapToInt(x -> x)
16
.min()
17
.orElseThrow(NoSuchElementException::new);
18
19
System.out.println("Min value = " + min); // 1
20
}
21
}
Output:
xxxxxxxxxx
1
Min value = 1