英文:
How can this code be improved with java streams
问题
以下是翻译好的部分:
我有一个需求,需要在给定的列表中查找是否有年龄超过18岁的用户。如果没有年龄超过18岁的用户,则该方法应返回-1。否则,它应返回年龄最小的用户。
在使用流时,我创建了以下方法,但流被使用了两次。是否有更好的方法可以使用流来完成这个任务?
public int test(List<User> userList) {
List<User> usersOver18 = userList.stream()
.filter(user -> user.getAge() > 18)
.collect(Collectors.toList());
if (usersOver18.isEmpty()) {
return -1;
}
return usersOver18.stream()
.min(Comparator.comparing(User::getAge))
.get().getAge();
}
英文:
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();
}
答案1
得分: 10
你可以映射到年龄,过滤掉任何小于或等于18岁的内容,然后返回最小值,如果流是空的则返回-1:
public int test(List<User> userList) {
return userList.stream()
.mapToInt(User::getAge)
.filter(age -> age > 18)
.min().orElse(-1);
}
需要注意的是,在mapToInt()
之后,你正在使用IntStream
而不是Stream<Integer>
,而min()
返回的是OptionalInt
,而不是Optional<Integer>
。
顺便问一下,你确定年龄过滤条件不是>= 18
吗?
英文:
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
?
答案2
得分: 3
我正在手机上凭记忆操作,所以可能不是完美的,但是...
return userList
.stream()
.filter(u -> u.getAge() > 18)
.min(Comparator.comparing(User::getAge))
.map(User::getAge)
.orElse(-1);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论