EN
Java 8 - find max and min value in List of objects
0 points
In this article, we would like to show you how to find maximum and minimum values in a list of custom objects in Java 8.
In this example, we use:
stream()
- to get a stream of values from theusers
list,max()
method on the stream - to get the maximum value- we are passing a custom comparator that specifies the sorting logic when determining the maximum value,
orElseThrow()
- to throw an exception if no value is received frommax()
method.
Practical example:
xxxxxxxxxx
1
import java.io.IOException;
2
import java.util.ArrayList;
3
import java.util.Comparator;
4
import java.util.List;
5
import java.util.NoSuchElementException;
6
7
8
public class Example {
9
10
public static void main(String[] args) throws IOException {
11
12
User user1 = new User("Tom", 20);
13
User user2 = new User("Kate", 21);
14
User user3 = new User("Ann", 22);
15
16
List<User> users = new ArrayList<>();
17
18
users.add(user1);
19
users.add(user2);
20
users.add(user3);
21
22
User maxAge = users
23
.stream()
24
.max(Comparator.comparing(User::getAge))
25
.orElseThrow(NoSuchElementException::new);
26
27
System.out.println(maxAge);
28
}
29
}
Output:
xxxxxxxxxx
1
User{ name='Ann', age=22 }
In this example, we use:
stream()
- to get a stream of values from theusers
list,min()
method on the stream - to get the minimum value- we are passing a custom comparator that specifies the sorting logic when determining the minimum value.
orElseThrow()
- to throw an exception if no value is received frommin()
method.
Practical example:
xxxxxxxxxx
1
import java.io.IOException;
2
import java.util.ArrayList;
3
import java.util.Comparator;
4
import java.util.List;
5
import java.util.NoSuchElementException;
6
7
8
public class Example {
9
10
public static void main(String[] args) throws IOException {
11
12
User user1 = new User("Tom", 20);
13
User user2 = new User("Kate", 21);
14
User user3 = new User("Ann", 22);
15
16
List<User> users = new ArrayList<>();
17
18
users.add(user1);
19
users.add(user2);
20
users.add(user3);
21
22
User minAge = users
23
.stream()
24
.min(Comparator.comparing(User::getAge))
25
.orElseThrow(NoSuchElementException::new);
26
27
System.out.println(minAge);
28
}
29
}
Output:
xxxxxxxxxx
1
User{ name='Tom', age=20 }
User.java:
xxxxxxxxxx
1
public class User {
2
private final String name;
3
private final int age;
4
5
public User(String name, int age) {
6
this.name = name;
7
this.age = age;
8
}
9
10
public String getName() {
11
return name;
12
}
13
14
public int getAge() {
15
return age;
16
}
17
18
19
public String toString() {
20
return "User{ " +
21
"name='" + name + '\'' +
22
", age=" + age +
23
" }";
24
}
25
}
26