如何使用 java 流改进此代码

Jav*_*Dev 1 java java-8 java-stream

我需要查找给定列表中是否有 18 岁以上的用户。如果没有超过 18 岁的用户,则该方法应返回 -1。否则,它应该返回最年轻用户的年龄。

在使用流时,我创建了以下方法,但是,流被使用了两次。有没有更好的方法来使用流来做到这一点

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();
}
Run Code Online (Sandbox Code Playgroud)

eri*_*son 10

您可以映射到年龄,过滤掉 18 岁或以下的任何内容,然后在流为空时返回最小值或 -1:

public int test(List<User> userList) {
    return userList.stream()
        .mapToInt(User::getAge)
        .filter(age -> age > 18)
        .min().orElse(-1);
}
Run Code Online (Sandbox Code Playgroud)

请注意,在之后mapToInt(),您正在使用IntStreamand not Stream<Integer>,并min()返回OptionalInt,not Optional<Integer>

顺便说一句,你确定年龄过滤器不是>= 18吗?