Java 8 Lambda expressions

(parameters) -> expression
(parameters) -> {statements;}

Examples from Java 8 Lambdas: Functional Programming For The Masses

Example 1

ActionListener oneArgument = new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent event) {
    System.out.println("button clicked");
  }
};
ActionListener oneArgument = event -> System.out.println("button clicked");

Example 2

Runnable noArguments = new Runnable() {
  @Override
  void run() {
    System.out.println("Hello World");
  }
};
Runnable noArguments = () -> System.out.println("Hello World");

Example 3

Runnable noArguments = new Runnable() {
  @Override
  void run() {
    System.out.print("Hello");
    System.out.println(" World");
  }
};
Runnable multiStatement = () -> {
  System.out.print("Hello");
  System.out.println(" World");
};

Example 4

BinaryOperator add = new BinaryOperator() {
  @Override
  public Long apply(Long x, Long y) {
    return x + y;
  }
};
BinaryOperator add = (x, y) -> x + y;
 
BinaryOperator addExplicit = (Long x, Long y) -> x + y;
This entry was posted in Java. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">