Posts

Showing posts from January, 2019

Understanding Java-8 method references with examples

In my previous post, I described about Lamda expression and its usages. Now I am going to write about method references in Java 8.

What is a method reference?

As I described in my previous post, a lamda expression is an anonymous function. However, sometimes lamda expression is only calling an existing method. On the other hand, if the function code in the lamda expression is too complicated or has many lines, it makes sense to include it in a separate method. This is when method references comes in handy. Instead of writing a lamda expression, we can refer to an existing method.

Based on the method type, there are 4 types of method reference syntax.

TypeSyntaxReference to a static methodContainingClass::staticMethodNameReference to an instance method of a particular objectcontainingObject::instanceMethodNameReference to an instance method of an arbitrary object of a particular typeContainingType::methodNameReference to a constructorClassName::new
Example usages

I am going to take the s…

Understanding Java Lamda Expression with examples

Lamda expression in Java was introduced in Java 8. This is one of my favorite, cool features of Java 8. This blog is intended to help understanding what is it, where and how can we use it.

What is lamda expression?

In simple words, Lamda expression in java is an anonymous function. It is defined with the parameter list and the function body.

Below is the syntax of lamda expression.


{parameter list}->{function body}

So what is actually meant by this definition? Although we define an anonymous function here, this is actually like an implementation to a method in an interface.

Also, we can assign this lamda expression to a reference of the interface type.

See example below.

interfaceMyInterface{public String sayWelcome(String name);}publicclassLamdaExpSample{publicstaticvoidmain(String args[]){ MyInterface myIn =(name)->{return"Welcome "+ name;};}}
As above, we have defined a Lamda expression to return a greet message. It has implemented the "sayWelcome" me…