Lambda Expression
Less than 1 minuteNoteLanguageJava
Java 8 feature
Anonymous function whose definition is not bound to an identifier
To replace anonymous inner class
Only works for
FunctionalInterface@FunctionalInterface interface MyLambda { void display(String s); } public class Main { public static void main(String[] args) { MyLambda m = (s) -> { System.out.println("Hello " + s); }; m.display("David"); } }Acting as an object
Local variables referenced from a lambda expression must be final or effectively final (not modified)
Instance variables can be accessed and modified
Use cases
RunnableComparatorListenerCollections
Very similar to arrow function in JavaScript
- Method references
Sometimes, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name
Kind Syntax Examples Reference to a static method ContainingClass::staticMethodNamePerson::compareByAgeMethodReferencesExamples::appendStringsReference to an instance method of a particular object containingObject::instanceMethodNamemyComparisonProvider::compareByNamemyApp::appendStrings2Reference to an instance method of an arbitrary object of a particular type ContainingType::methodNameString::compareToIgnoreCaseString::concatReference to a constructor ClassName::newHashSet::new
