Java 8 Stream – Converting For Loop to Stream Example

for-loopjavajava-8java-stream

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;
}

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.

Any suggestions?

Best Answer

Using the newest IntelliJ IDEA 2016.3 EAP (either Community edition or Ultimate edition), you can convert it automatically. Just put the cursor on your for-loop:

Idea

Press the Alt-Enter and select "Replace with findFirst()":

Idea

Voila, it's done!

Idea

Disclaimer: I'm IntelliJ IDEA developer.

Related Question