DEV Community

Cover image for Lambda Expression
groundlevelgeek
groundlevelgeek

Posted on

Lambda Expression

Hello Java Programmers

Java 1.8 SE brings to us many new features, But among these features, one shouts more than any other feature is... guess What?? Yeah, you got that! Lambda Expression.

Java has been all around OOP concepts, Are we really going to start functional programming using lambda expression in java??

OK! First let us try to understand and break down lambda expression in simplified way, to fit this new terminology in our brain.

So what do we understand by an expression? An expression is nothing but a calculus statment in mathematics, gives us some result, when we feed some value to it.

Like an expression:

result = (a+b)^2;

So here we have a statement, we as java programmer write statements everywhere in java.

Is that mean? All statements we are writing in java world, are Lambda Expressions/Statements.

Of course, all your statements can be a Lambda Expression/Statement. But what special thing in java, makes a statement a lambda expression/statement?

The special thing is Type, Yes you read correctly!

Java is all about Type/Class. If you write a statement and this statement is of some type, Yess you got that, It is Lambda Expression/Statement.

But here you might think as a java programmer, I write statements of course but all I do have to write inside a method/function. Therefore no statement is directly of any type. They are inside some method and that method in turn, belongs to a class/Type. Then how a statement could be of a Type? Wondering..??

Let's see a java method chunk

public class Application{

 public void printActiveEmployee(){
    System.out.println('Mark Mahindra');
 }
}

Here, the statement is inside the method, and the method is written obviously inside a class, which means, method belongs to a type but not the statement. The statement belongs to the method.

i.e. No Statement is of any Type??

Yes The Statements, We are writing, for methods, not for any type.

Then what is the blocker to make my statement becoming of any type, What?? Yes, That is a method/function.

If somehow, It is possible to remove the method, my statements written inside it, will directly belong to the Class/Type.

Let's see how Java Developers/Creator have thought to remove the method. What a method typically has??

Access Modifier > Return Type > Name > Parameters > Body

public void printActiveEmployee(){
    System.out.println('Mark Mahindra');<br>
}

Here,

  1. public -> Access Modifier
  2. void -> Return Type
  3. 'printEmployee' -> Method Name

They just remove all these three things from a method and leave you with Parentheses and Body.

  (){
      System.out.println('Mark Mahindra');
   }

Here, you will just add just an arrow '->' into this syntax.

And of course, if this left syntax () -> {} not under any method, therefore it directly belongs to the type/class, it is written inside.

In our world, Anything without a name is known as Anonymous. A person without a name is an anonymous person, a thing without a name is an anonymous thing, so a method without the name, is an anonymous method.

So If we write a method without describing Access Specifier, Return type, and Method Name, It is a an Anonymous method/function, Just with Parentheses and Body () -> {}.

Yeah, so far now, we have our syntax of Lambda Expression.
So we can say a method without a name is lambda expression/statement because it is directly under the Class/Type, So this statement is of that Type.

But here is a twist, Java Classes have not evolved yet, to support any behavior/statement written directly inside the class, i.e. without its wrapper 'Method'.

So how do we give a Type to my anonymous method or statements, that I want to write as anonymous, How?

Here comes Interface to rescue. The interface can allow writing, its method implementation, or statements without having its name, return type, and access modifiers. Same as anonymous right?

So if I write an Interface having a method, I can implement this method as anonymous method/function or nothing but Lambda Expression.

Let's see this

public interface MyInterf {
  public void greetJavaProgrammer();
}

Now let's write anonymous statements for this method.

public class Application {

MyInterf myInterf = () -> {
              ... // write your statements here
            };
myInterf.greetJavaProgrammer();

}

Yes, This anonymous statement is our Lambda Expression.

So now we know that Interface's method can be written as a Lambda expression/statement.

Why wait! create your interface and write a lambda expression it.

Wait A Bit! An Interface may have many abstract methods.

So if we write lambda expression for an interface's method, how does Java/Java Compiler (after all it is responsible for codes) know that we are writing statements(lambda expression) for which method and we have already seen lambda expression does not explicitly tell anything about method name and all.

So how Java is marking my Lambda expression, is for one particular method among declared methods in the interface.

So here is the constraint comes, Java Compiler can not do that. It can not assign a lambda expression to a particular method if that interface has more than one abstract method. It gets confusing.

Therefore The Interface which has only one abstract method, can be written as Lambda expression/statement. Because Java Compiler knows there is the only method inside the interface, you writing lambda expression to. No ambiguity for Java Compiler right?

And in fact, every Java Programmer know that the Interface having only one abstract method is the Functional Interface.

That means, Only Functional Interface can be written as Lambda expression/statement.

So happily from now, create your functional interface and write lambda for this interface/interface's method.

Tip: If you wanna make any interface a functional interface, keep only one abstract method in it. And if you do not wanna permit any other programmer to make it nonfunctional interface, you may add @FunctionalInterface annotation on this Interface, so java assures you, No one can add anymore abstract method to this interface, even by accidently.

Java has given us a few pre-defined Functional Interfaces to use them as utility and Java itself using these interfaces in it's library/APIs.

A few are listed below: (with abstract method available)

  1. Predicate<T>     - boolean test(T t)
  2. Function<T, R>  - R apply(T t)
  3. Consumer<T>   - void accept(T t)
  4. Supplier<R>       - R get()

There are many other flavours available of these Functional Interfaces, But this is something, I would surely like to come with in our next knowledge transfer.

Conclusion:

1. Functional Interface can be written as a lambda expression/statement.

2. @FunctionalInterface annotation to restrict/force the interface to be an ideal functional interface.

3. We can write our custom functional interface and then write a lambda expression/statement for that.

4. There are a few pre-defined functional interfaces in java as a utility.

Meet you later!

Top comments (0)