Skip to main content

Posts

Showing posts with the label java lambda example

Java 8 - Method references

This article is in continuation to my other posts on Functional Interfaces , static and default methods and Lambda expressions . Method references are the special form of Lambda expression . When your lambda expression are doing nothing other than invoking existing behaviour (method), you can achieve same by referring it by name. :: is used to refer to a method. Method type arguments are infered by JRE at runtime from context it is defined. Types of method references Static method reference Instance method reference of particular object Instance method reference of an arbitrary object of particular type Constructor reference Static method reference When you refer static method of Containing class. e.g. ClassName::someStaticMethodName class MethodReferenceExample { public static int compareByAge(Employee first, Employee second) { return Integer.compare(first.age, second.age); } } Comparator compareByAge = MethodReferenceExample::compareByAge; Instanc

Java 8 - Lambda expressions

In this post, we will cover following topics. What are Lambda expressions? Syntax for Lambda expression. How to define no parameter Lambda expression? How to define single/ multi parameter Lambda expression? How to return value from Lambda expression? Accessing local variables in Lambda expression. Target typing in Lambda expression. What are Lambda expressions? Lambda expressions are the first step of Java towards functional programming. Lambda expressions enable us to treat functionality as method arguments, express instances of single-method classes more compactly. Syntax for Lambda expression Lambda has three parts: comma separated list of formal parameters enclosed in parenthesis. arrow token -> . and, body of expression (which may or may not return value). (param) -> { System.out.println(param); } Lambda expression can only be used where the type they are matched are functional interfaces . How to define no parameter Lambda expression? If the la