Java 8 Lambda Expression Basic Syntax and Examples

Lambda expressions implement an interface with only one single abstract methodl. Such interfaces are called as functional interfaces. Since the interface has only one single method (function), passing across that interface implementation gives the impression of passing across that function. Already existing interfaces in Java such as Runnable, Comparator, ActionListener are already functional interfaces, as they have only one abstract method. We will see how we can use lambda expressions with those existing interfaces.

 

Basic syntax

Basic syntax of lambda expression is:

(input arguments) -> body.

The body may return anything in accordance to the return type of the functional interface. In case, if the body contains more than one statements, those statements can be put within curly braces. 

 

Example: Runnable Interface

Before

<NEED-TO-ADD>

 

With Lambda expression

new Thread( () -> System.out.println("Hello from run.")).start();

 

Example: Comparator

Before

Collections.sort(stringList, new Comparator<String> ()){

@Override

public int compare(String s1,String s2){

    return s1.compareToIgnoreCase(s2);

}

});

 

With Lambda expression:

Comparator <String> c = (s1,s2) ->  return s1.compareToIgnoreCase(s2);

Collections.sort(stringList,c);

 

Example: Swing ActionListener

Before:

button.addActionListener (new ActionListener() ){

public void actionPerformed( ActionEvent event){

  System.out.println(“button clicked”);

}

});

 

With Lambda expression:

button.addActionListener ( event -> System.out.println(“button clicked”);

Note that event is the name of the parameter which can be used within code and its type is inferred from context automatically by Java.

 

TODO

  • Give exampe for Callable (Single line and multi-line)

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!