What are lambdas?
The Java programming language supports lambdas as of Java 8. A lambda expression is a block of code with parameters. Lambdas allows to specify a block of code which should be executed later. If a method expects a functional interface as parameter it is possible to pass in the lambda expression instead.
The type of a lambda expression in Java is a functional interface.
Purpose of lambda expressions
Using lambdas allows to use a condensed syntax compared to other Java programming constructs. For example the
Collection
interfaces has forEach
method which accepts a lambda expression.List<String> list = Arrays.asList("microsoft.com","google.com","heise.de" )list.forEach(s-> System.out.println(s));
20.3. Using method references
You can use method references in a lambda expression. Method reference define the method to be called via
CalledFrom::method
. CalledFrom can be * instance::instanceMethod * SomeClass::staticMethod * SomeClass::instanceMethodList<String> list = new ArrayList<>();
list.add("microsoft.com");
list.add("google.com");
list.add("heise.de");
list.forEach(System.out::println);
20.4. Difference between a lambda expression and a closure
The Java programming language supports lambdas but not closures. A lambda is an anonymous function, e.g., it can be defined as parameter. Closures are code fragments or code blocks which can be used without being a method or a class. This means that a closure can access variables not defined in its parameter list and that it can also be assigned to a variable.
No comments:
Post a Comment