Back to home

Example
Java Lambda Functions main image

Java Lambda Functions

The basic gist is to generate a interface with the lambda signature, then explicitly create a function preface by the interface type.

This will allow you to call the lambda function as a instance method.

Example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // src/main/java/Lambda.java interface Anon { String helloWorld(); } interface AnonInt { int sum(int a, int b); } class Lambda { String hello() { Anon anon = () -> "Hello, World!"; return anon.helloWorld(); } int sumOnePlusTwo() { AnonInt anon = (int a, int b) -> a + b; return anon.sum(1, 2); } }

As for the test file:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // src/tests/java/LambdaTest.java import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; public class LambdaTest { @Test public void testLambda() { assertEquals("Hello, World!", new Lambda().hello()); } @Test public void testLambdaSum() { assertEquals(3, new Lambda().sumOnePlusTwo()); } }

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.