Takichiii Takichiii - 6 months ago 27
Java Question

From for loop to Java 8 Stream example

I would like a simple example for Java 8

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
, and evaluate if
respects the condition. If the condition applies, I stop the loop and return

Any suggestions?


What you are looking for is this:

return taxis.stream()

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

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

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

filter(t -> t.isFree())

or using a lambda expression block:

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>() {
    public boolean test(Taxi t) {
        return t.isFree();

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();