January 2, 2017

Java 8 - Lambda Expressions

Syntax

parameter -> expression body
  • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
  • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
  • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.

Examples

Old inner class

new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println(" >> Hello from thread");
    }
}).start();

With lambda expression

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

Old inner class

List<String> strings1 = Arrays.asList(new String[] { "foo", "bar" });
Collections.sort(strings1, new Comparator<String>() {

    @Override
    public int compare(String s1, String s2) {
        return s1.compareTo(s2);
    }
});
assertThat(Arrays.asList(new String[] { "bar", "foo" }), is(equalTo(strings1)));

With lambda expression

List<String> strings2 = Arrays.asList(new String[] { "foo", "bar" });
Collections.sort(strings2, (s1, s2) -> s1.compareTo(s2));
assertThat(Arrays.asList(new String[] { "bar", "foo" }), is(equalTo(strings2)));

No comments: