Coffee Talk: Java, News, Stories and Opinions

Dec 13 2018   1:30PM GMT

Learn Java lambda syntax quickly with these examples

cameronmcnz Cameron McKenzie Profile: cameronmcnz

Tags:

For those who are new to functional programming, basic Java lambda syntax can be a bit intimidating at first. Once you break lambda expressions down into their component parts, though, the syntax quickly makes sense and becomes quite natural.

The goal of a lambda expression in Java is to implement a single method. All Java methods have an argument list and a body, so it should come as no surprise that these two elements are an important part of Java lambda syntax. Furthermore, the Java lambda syntax separates these two elements with an arrow. So to learn Java lambda syntax, you need to be familiar with its three component parts:

  1. The argument list
  2. The arrow
  3. The method body

To apply these concepts, we first need a functional interface. A functional interface is an interface that only defines a single method that must be implemented. Here is the functional interface we will use for this example:

interface SingleArgument {
   public void foo(String s);
}

An implementation of this method requires a String to be passed in and a body that performs some logic on the String. We will break it down into its constituent elements in a moment, but for now, here’s a very basic example in which a lambda provides an implementation to the SingleArgument interface, along with a couple of invocations of the interface’s foo method:

SingleArgument sa1 =  n -> System.out.print(n);
sa1.foo("Let us all");
sa1.foo(" learn lambda syntax");

The following is a complete class implementing this logic:

package com.mcnz.lambda;

public class LearnJavaLambdaSyntax {
	
   public static void main(String args[]) {	
      SingleArgument sa1 =  n -> System.out.print(n);
      sa1.foo("Let us all");
      sa1.foo(" learn lambda syntax");
   }
}

interface SingleArgument {
   public void foo(String s);
}

Concise and verbose Java lambda syntax

The implementation demonstrated here is highly abbreviated. This can sometimes make it a bit difficult for newcomers to learn Java lambda syntax. It is sometimes helpful, then, to add a bit more ceremony to the code. One enhancement that can make it easier to learn Java lambda syntax is to put round brackets around the method signature and include type declarations on the left-hand side:

SingleArgument sa2 =  (String n) -> System.out.print(n) ;

Furthermore, you can put curly braces around the content on the right-hand side and end each statement with a semi-colon.

SingleArgument sa3 =  (String n) -> { System.out.print(n); } ;
learn java lambda syntax

Compare these different approaches to learn Java lambda syntax.

Multi-line lambda expression syntax

In fact, if your method implementation has more than a single statement, semi-colons and curly braces become a requirement. For example, if we wanted to use a regular expression, strip out all of the whitespace before printing out a given piece of text, our Java lambda syntax would look like this:

(String n) -> {
    n = n.replaceAll("\\s","");
    System.out.print(n);
}

Multi-argument lambda functions

In this example, the method in the functional interface has only one argument, but multiple arguments are completely valid, so long as the number of arguments in the lambda expression match the number in the method of the functional interface. And since Java is a strongly typed language, the object types must be a polymorphic match as well.

Take the following functional interface as an example:

interface MultipleArguments {
   public void bar(String s, int i);
}

The highly ceremonial Java lambda syntax for implementing this functional interface is as follows:

MultipleArguments ma1 = (String p, int x) -> {
   System.out.printf("%s wants %s slices of pie.\n", p, x);
};

As you can see, this lambda expression leverages multiple arguments, not just one.

I described this example as being highly ceremonial because we can significantly reduce its verbosity. We can remove the type declarations on the left, and we can remove the curly braces and the colon on the right since there is only one instruction in the method implementation. A more concise use of Java lambda syntax is as follows:

( p, x ) -> System.out.printf ( "%s wants %s slices.\n", p, x )

As you can see, Java lambda syntax is quite a bit different from anything traditional JDK developers are used to, but at the same time, when you break it down, it’s easy to see how all the pieces fit together. With a bit of practice, developers quickly learn to love Java lambda syntax.

Here is the full listing of code used in this example:

package com.mcnz.lambda;

public class LearnJavaLambdaSyntax {
	
  public static void main(String args[]) {
		
    SingleArgument sa1 =  n -> System.out.print(n);
    sa1.foo("Let us all ");
    sa1.foo("learn Java lambda syntax.\n");

    SingleArgument sa2 =  (String n) -> System.out.print(n);
    sa2.foo("Java lambda syntax ");
    sa2.foo("isn't hard.\n");
		
    SingleArgument sa3 =  (String n) -> { System.out.print(n); };
    sa3.foo("You just need a few ");
    sa3.foo("good Java lambda examples.\n");
		
    SingleArgument sa4 =  (String n) -> {
      n = n.replaceAll("\\s","");
      System.out.print(n);
    };
    sa4.foo("This Java lambda example ");
    sa4.foo("will not print with whitespace.\n");
		
    MultipleArguments ma1 = (String p, int x) -> {
      System.out.printf("%s1 wants %s2 slices of pie.\n", p, x);
    };
    ma1.bar("Cameron ", 3);
    ma1.bar("Callie", 4);
		
    MultipleArguments ma2 = 
      ( p, x ) -> System.out.printf ( "%s1 wants %s2 slices.\n", p, x );
    ma2.bar("Brandyn", 1);
    ma2.bar("Carter", 2);
	
  }

}

interface SingleArgument {
  public void foo(String s);
}

interface MultipleArguments {
 public void bar(String s, int i);
}

When this Java lambda syntax example runs, the full printout is:

Let us all learn lambda syntax.
Java lambda syntax isn't hard.
You just need a few good Java lambda examples.
ThisJavalambdaexamplewillnotprintwithwhitespace.Cameron 1 wants 32 slices of pie.
Callie1 wants 42 slices of pie.
Brandyn1 wants 12 slices.
Carter1 wants 22 slices.

You can find the source code used in this tutorial on GitHub.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: