Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Originally published atgunnargissel.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 modeExit 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 modeExit fullscreen mode

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
evanoman profile image
Evan Oman
  • Email
  • Location
    Minnesota
  • Education
    Masters in Applied Math
  • Work
    Software Engineer at Black River Systems Co.
  • Joined

TheJava lambda syntax allows single line statementsor statement blocks which can be arbitrarily long. So theisBark predicate is good and reusable but you could stuff as many lines as you like into the lamba:

Predicate<Animal>isDog=animal->{try{Soundsound=animal.getSound();returnsound.equals(Sound.valueOf("bark"));}catch(MuteAnimalExceptione){logger.severe(e.getMessage);returnfalse;}};
CollapseExpand
 
monknomo profile image
Gunnar Gissel
Saving fish by writing code! Applications developer in fisheries, specializing in webapps and moving 'enterprise-y' legacy systems to modern agile systems - Email or tweet me if you want to talk!
  • Email
  • Location
    Alaska
  • Education
    Bachelor's in Physics
  • Work
    Application Developer at NOAA
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Saving fish by writing code! Applications developer in fisheries, specializing in webapps and moving 'enterprise-y' legacy systems to modern agile systems - Email or tweet me if you want to talk!
  • Location
    Alaska
  • Education
    Bachelor's in Physics
  • Work
    Application Developer at NOAA
  • Joined

More fromGunnar Gissel

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp