从for循环到Java 8 Stream示例 [英] From for loop to Java 8 Stream example

查看:117
本文介绍了从for循环到Java 8 Stream示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个简单的Java 8 Streams示例来理解它.我有此代码可返回免费出租车.我想用使用Java 8流的等效代码替换此for循环:

I would like a simple example for Java 8 Streams to understand it. I have this code that returns a free taxi. I would like to replace this for loop with equivalent code that uses Java 8 streams :

private List<Taxi> taxis = new ArrayList<Taxi>();

Taxi scheduleTaxi(){
    for (Taxi taxi : taxis) {
        if (taxi.isFree()) {
            return taxi;
        }
    }
    return null;
}

我遍历taxis的列表,并评估taxi是否符合条件.如果条件适用,我将停止循环并返回taxi.

I iterate over a list of taxis, and evaluate if taxi respects the condition. If the condition applies, I stop the loop and return taxi.

有什么建议吗?

推荐答案

您正在寻找的是这个东西

What you are looking for is this:

return taxis.stream()
            .filter(Taxi::isFree)
            .findFirst()
            .orElse(null);

这是表达式步骤及其返回类型的列表,以及与javadoc的链接:

Here is a list of the expression steps with their return type and links to javadoc:

表达步骤       | 类型                   | 替代
taxis                          | List<Taxi>
stream()   ;                     | Stream<Taxi>     | parallelStream()
filter(Taxi::isFree) | Stream<Taxi>
findFirst()                 | Optional<Taxi> | findAny()
orElse(null)               | Taxi                  | 无,见下文

Expression Step         | Type                    | Alternative
taxis                           | List<Taxi>
stream()                      | Stream<Taxi>     | parallelStream()
filter(Taxi::isFree) | Stream<Taxi>
findFirst()                 | Optional<Taxi> | findAny()
orElse(null)               | Taxi                   | none, see below

filter(Taxi::isFree)调用使用的是 方法参考 .
也可以使用 lambda表达式编写:

The filter(Taxi::isFree) call is using a method reference.
It can also be written using a lambda expression:

filter(t -> t.isFree())

或使用 lambda表达式块:

filter(t -> {
    return t.isFree();
})

该参数还可以指定类型,更明确地说:

The parameter can also specify a type, to be more explicit:

filter((Taxi t) -> { return t.isFree(); })

使其看起来更像 匿名类 等效于:

which makes it look more like the anonymous class it's equivalent to:

filter(new Predicate<Taxi>() {
    @Override
    public boolean test(Taxi t) {
        return t.isFree();
    }
})


如@ 4castle 在评论中提及,具体取决于需要scheduleTaxi()方法时,您可能需要更改返回类型并跳过最后一步,以向调用者明确表明它可能找不到出租车.


As @4castle mentioned in a comment, depending on the needs of your scheduleTaxi() method, you might want to change the return type and skip the last step, to make it explicit to the caller that it might not be able to find a taxi.

Optional<Taxi> scheduleTaxi() {
    return taxis.stream().filter(Taxi::isFree).findFirst();
}

这篇关于从for循环到Java 8 Stream示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆