dreamsys software

Java 8 Lambda Expressions Tutorial


The purpose of this tutorial is to show you how to use the new lambda expressions available in JDK 8. You can download the latest build of JDK 8 at http://jdk8.java.net/lambda/.

We are going to start with a simple example. Anyone who has done threading in java is familiar with the Runnable interface, which can be given to a Thread to run the code within the run method on a separate thread. Let's take a look at the old way to do this and the new way. The first variable r1 is an instance of a Runnable interface done the old way, the second variable r2 is how you do it with lambda expressions.

public class ThreadTest {
  public static void main(String[] args) {
    Runnable r1 = new Runnable() {
      public void run() {
        System.out.println("Old Java Way");

    Runnable r2 = () -> { System.out.println("New Java Way"); };

    new Thread(r1).start();
    new Thread(r2).start();

Notice that we take all of the boilerplate code which we write every time and get rid of it all with a simple expression. In face, the code to start the thread could even be simplified further as:

new Thread(() -> System.out.println("New Java Way")).start();

In the next section, we will show how to use a comparator the Java 8 way.

Prev (TOC) | Next (Comparator)

Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6