如何使用Java流改进此代码?

huangapple go评论59阅读模式
英文:

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&lt;User&gt; userList) {
    List&lt;User&gt; usersOver18 = userList.stream()
            .filter(emp -&gt; emp.getAge() &gt; 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&lt;User&gt; userList) {
    return userList.stream()
        .mapToInt(User::getAge)
        .filter(age -&gt; age &gt; 18)
        .min().orElse(-1);
}

Note that after mapToInt(), you are working with an IntStream and not Stream&lt;Integer&gt;, and min() returns OptionalInt, not Optional&lt;Integer&gt;.

By the way, are you sure the age filter is not &gt;= 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 -&gt; u.getAge() &gt; 18)
    .min(Comparator.comparing(User::getAge))
    .map(User::getAge)
    .orElse(-1);

huangapple
  • 本文由 发表于 2020年9月3日 09:56:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63715714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定