Lambda Expressions in Java - the most under-rated topic

Green and Black Simple & Circular Online Event Logo.jpg

Many features were added in java since its initial release. however, the two that stand out most in reshaping this language were generics and lambda expressions. The lambda expressions added two new capabilities:-

  • They added new syntax element that increases the expressive power of language
  • New capabilities were incorporated that easily take advantage of parallel processing capabilities of multi-core.

Lambda expressions are underused by java programmers. This topic is ignored by new programmers.
So, let's get to know them better.

What are Lambda Expressions?
They are anonymous i.e unnamed methods. However, these methods are not executed on their own rather they are used to implement a method defined by a functional interface. Now the question arises what are these functional interfaces.

Interface
It is a completely "abstract class" that is used to group abstract methods together.

Functional Interface
It is an interface that contains one and only abstract method. For example, Runnable is a functional interface that contains only 1 method run().

Lambda Expression Fundamentals
Lambda expression introduces a new operator sometimes referred to as Lambda operator or arrow operator "->". It divides lambda expression into two parts. The left side specifies any parameters required by the lambda expression. And the right side is the lambda body, which specifies the actions of the lambda expression. Let us understand it better.

Java
() -> 123.45 . It is similar to the method
double myMeth(){return 123.45;}


(n) -> (n%2)==0
This lambda expression takes parameter n and returns true or false based on the value of n.

Hope you would have understood the basic syntax of lambda expressions. Now, let us visualize them with the help of a program.

Java

//functional interface
interface MyVal{
    double getNumber();
}

class ABC{
 public static void main(String args[]){
   MyVal val; // declaring interface reference
   val = () -> 123.45;
   System.out.println(val.getNumber()); 
}
}

Advantages of lambda expressions

  • Fewer line of code
  • Higher efficiency
H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now