Lambda expression in replace of anonymous class in Java

As of Java 8 a new expression was added to the Java language, the lambda expression. This example shows how to use a lambda expression instead of using an anonymous class. More specifically when declaring an ActionListener to be called when a button is pressed.

The old way with an anonymous class

The code below shows how to add an ActionListener the ‘traditional’ way, namely creating a new instance of ActionListener and overriding its actionPerformed method:

If you run the example and press the button a few times the output looks something like this (the time will of course be different):

Using lambda expression

Instead of creating the ActionListener class, we can use a lambda expression.
The code above that looks like this:

is replaced by this:

or even simpler:

Full code:

When run the frame with the button looks like this:

A frame with a button

As we can see from the output it works in the same way as the first example, namely writing out the param string of the event if the button is pressed:

More about lambda expressions:

Lambda expressions – method references

Search for more Java info on this site here:
Custom Search

Please type any questions here.