Experimenting with Java lambda syntax

On the lambda dev forum it was announced the Java lambda syntax ( planned for Java 8 ) will be based on the C# syntax., it will use thin arrow “->” rather C#’s fat arrow “=>” . I was curious to see what Java code with lambdas will look like using Swing.

To experiment with lambda, you can use a special build of the JDK with lambda support

http://jdk8.java.net/lambda/

To compile java files using the lambda features, nake sure you using javac is taken from the bin directory of this lambda jdk build.

Below is the non lambda version of the Example – using anonymous inner classes for the ActionListener and for the Runnable.

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class TestInnerClass{

public static void showUI()
{
JFrame frame = new JFrame("Anonymous Inner Class Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click Me");

button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
}
);

Container contentPane = frame.getContentPane();
contentPane.add(button, BorderLayout.CENTER);
frame.setSize(300, 100);
frame.setVisible(true);
}

public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
showUI();
}
});

}
}

 

The above is not very interesting, now let’s convert those inner classes to use the lambda syntax..

 

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class TestLambda{

public static void showUI()
{
JFrame frame = new JFrame("Lambda Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click Me");

button.addActionListener( (e) -> {System.out.println("button clicked");});

Container contentPane = frame.getContentPane();
contentPane.add(button, BorderLayout.CENTER);
frame.setSize(300, 100);
frame.setVisible(true);
}

public static void main(String[] args)
{
SwingUtilities.invokeLater(() -> {showUI();});

}
}

 
Using the lambda syntax, the code looks more concise, it has less ceremony (code that offers very little information).

One Reply to “Experimenting with Java lambda syntax”

Leave a Reply

Your email address will not be published. Required fields are marked *