Channels ▼

Eric Bruno

Dr. Dobb's Bloggers

JDK: Getting A Head Start with Lambdas

September 28, 2012

What are Lambda Expressions? They're part of Java's Project Lambda, whose goal is to add support for closures to the Java programming language. In a sentence, a closure allows a piece of code to reference the variables of another method or function without being within the scope of that method or function. The OpenJDK site states that Lambda expressions can only appear in places where they'll be assigned to a variable whose type is a functional interface. Two simple examples provided are:

Runnable r = () -> { System.out.println("hello"); };


Collections.sort(strings, (String a, String b) -> -(a.compareTo(b)));

The first example assigns a function whose implementation outputs the text "hello" to r, which is a Runnable. The second example uses a closure (Java Lambda Expression) to implement a Comparator method for sorting a collection of Strings. JDK 8's implementation of closures depends on Java SE 7's newly added Invokedynamic. This makes sense, since closures are usually associated with dynamic, functional languages, and Invokedynamic was added to Java to support code written in those languages (i.e., Groovy, Ruby, and so on).

For a more in-depth explanation of how Lambdas are implemented in JDK, read Brian Goetz's excellent write-up here.

Try Lamdas Now!

Admittedly, the syntax for Lambdas takes some getting used to. The best way to learn is through doing. Want to try it for yourself? You can download an early access copy of JDK8 here. There are versions available for Solaris, Windows, Linux, and Mac OS X.

To use Lambdas, you must apply a secondary download patch over the standard JDK8 install. Download the files appropriate for your platform here.

Set this Java installation as your Java platform in Eclipse or NetBeans, and you're ready to write some closures. Don't forget to also set your compiler to generate JDK8 code. For NetBeans, add a Java Platform via the Platform Manager (see Figure 1 below).

Figure1 NB

Next, set this as your platform in your project's settings, as shown in Figure 2 below.

Figure2 NB

Next, let's write a Lambda Expression. Prior to JDK8, to provide a Runnable to a Thread using something close to a closure, you could write a nested class as such:

  Thread t1 = new Thread( 
          new Runnable() {
              public void run() {
                  System.out.println("Thread t1");

Not bad, but it's a little verbose for an interface with just one method. The same thing can be accomplished with a Lambda Expression like this:

  Thread t2 = new Thread( () -> { System.out.println("Thread t2"); } );

Much less verbose. The use of a Runnable in Thread's constructor is implied here. A more explicit way to do this is to declare the Runnable first, and then provide that to Thread as such:

  Runnable r = () -> { System.out.println("I'm a Runnable!"); };
  Thread t3 = new Thread( r );

Note that if you add this code to a project in NetBeans set to the proper JDK8 installation, you'll get red squiggly lines falsely indicating an error within the NetBeans editor. However, barring an actual syntax error, your new Lambda code should build and run just fine.

You'll also notice that although this code compiles fine, it won't run in NetBeans by default. You can do one of two things here to resolve this. The first is a workaround: You can run your project from the command line specifying JDK8's java to launch your application. The second, and better, option is to simply turn off NetBean's Compile on Save option within your project's Build->Compiling project settings (see Figure 3). Now you can actually code and run (or debug) your JDK8 project with Lambdas from within NetBeans. Go ahead, set a breakpoint, and you should be able to step through each line without issue.

Figure4 NB

You're now up and running with JDK8, and are free to use Lambda Expressions to learn all about them before they're official. As time goes on and JDK8 shapes up more, we'll explore Lambda Expressions deeper as well other new features. Remember not to use JDK8 for any production code as it's still in development.

Happy coding!

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.