<-- Twitter Summary card images must be at least 120x120px -->

How to Write a Multiline Lambda in Java 8

A short example of how to make multiline lambda functions in Java 8

For the most part, single line lambda functions are all you need.

This is a single line lambda:

Predicate<String> isBig = str -> str.length() > 10;

Sometimes one line is not enough to express the complexity of the lambda. How do you make a multiline lambda?

This is how:

//set up - elsewhere in the pseudo code:
public Sound getSound() throws MuteAnimalException {...}
Predicate<Sound> barks = sound -> Sound.valueOf("bark").equals(sound);


//payoff, a multiline lambda
Predicate<Animal> isDog = animal -> {
    try {
        return barks.test(animal.getSound());
    } catch (MuteAnimalException e){
        logger.severe(e.getMessage);
        return false;
    }
};