Reputation: 29
I have a requirement to find if there are any Users over the age of 18 in the given list. If there is no user over age 18, the method should return -1. Otherwise, it should return the age of the youngest user.
While using the streams, I created the following method, however, the stream is used twice. Is there a better way to do this with streams
public int test(List<User> userList) {
List<User> usersOver18 = userList.stream()
.filter(emp -> emp.getAge() > 18)
.collect(Collectors.toList());
if (usersOver18.isEmpty()) {
return -1;
}
return usersOver18.stream()
.min(Comparator.comparing(User::getAge))
.get().getAge();
}
Upvotes: 1
Views: 146
Reputation: 269667
You can map to the age, filter out anything 18 or under, and then return the minimum or -1 if the stream is empty:
public int test(List<User> userList) {
return userList.stream()
.mapToInt(User::getAge)
.filter(age -> age > 18)
.min().orElse(-1);
}
Note that after mapToInt()
, you are working with an IntStream
and not Stream<Integer>
, and min()
returns OptionalInt
, not Optional<Integer>
.
By the way, are you sure the age filter is not >= 18
?
Upvotes: 10
Reputation: 2685
I'm doing this from memory on my phone so it might not be perfect, but...
return userList
.stream()
.filter(u -> u.getAge() > 18)
.min(Comparator.comparing(User::getAge))
.map(User::getAge)
.orElse(-1);
Upvotes: 3