DEV Community

Cover image for How to Write a Multiline Lambda in Java 8
Gunnar Gissel
Gunnar Gissel

Posted on • Originally published at gunnargissel.com on

How to Write a Multiline Lambda in Java 8

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

This is a single line lambda:

Predicate<Sound> isBark = sound -> Sound.valueOf("bark").equals(sound); 
Enter fullscreen mode Exit fullscreen mode

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 Animal interface: 
public Sound getSound() throws MuteAnimalException {...} 
Predicate<Sound> isBark = sound -> Sound.valueOf("bark").equals(sound); 
//payoff, a multiline lambda 
Predicate<Animal> isDog = animal -> { 
    try { 
        return isBark.test(animal.getSound()); 
    } catch (MuteAnimalException e){ 
        logger.severe(e.getMessage); return false; 
    } 
};
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
evanoman profile image
Evan Oman

The Java lambda syntax allows single line statements or statement blocks which can be arbitrarily long. So the isBark predicate is good and reusable but you could stuff as many lines as you like into the lamba:

Predicate<Animal> isDog = animal -> { 
    try {
        Sound sound = animal.getSound();
        return sound.equals(Sound.valueOf("bark")); 
    } catch (MuteAnimalException e){ 
        logger.severe(e.getMessage); return false; 
    } 
};
Collapse
 
monknomo profile image
Gunnar Gissel

That is true, and reminds me of a change I had thought of for my single line lambda demo. brb, editing example