Skip to main content

Lambda in java

Java is to JavaScript what car is to Carpet
– Chris Heilmann

Hello to all the java enthusiast out there! Today I will talk about lambda's in java and about colon operators.
So What exactly is a lambda?
Simply put, it is a function without any name, any return type or any modifier. Let us understand with a simple example
    public void divide(int a , int b) {
        System.out.println(a/b);
    }
The above code has the following attributes :
  1. Name : divide
  2. Modifier : public
There is no return type here. For lambda, we will remove these first as -
    (int a , int b) {
        System.out.println(a/b);
    }

If you have some knowledge about lambda's, you might think - Hey ! Where are those arrow things? We add them after the parameters :
    (int a , int b) -> {
        System.out.println(a/b);
    }
But we, also have type inference in java, which means the parameter types can be infered by the compiler on its own. In simple terms this means that we do not need types of parameters as well.
    (a , b) -> {
        System.out.println(a/b);
    }
Congratulations! You created your first lambda!

How do we get invoke these methods and where do we declare them?

For this we use the concept of funtional interfaces.
A functional interface is an interface that contains single abstract method.We can have any number of static and default methods

How to create a functional interface?

We use @FunctionalInterface from java.lang package.Let us dig deeper in this concept with an example without using lambda-
    @FunctionalInterface
    public interface interfaceWithoutLambda {
        public void test(); ---> This is an abstract method
    }
We create another class to implement this interface
    class classWithoutLambda implements interfaceForLambda {
    @Override
    public void test() {
      System.out.println("This is a trivial way to implement before lambda");
    }
  
Then we create a main class as 
    class mainClass { 
         public static void main(String args[]) { 
             classWithoutLambda obj = new classWithoutLambda(); 
             obj.test(); 
     }
    }
Now, with lambda we do not need the class to implement the interface and define the method. We skip implementing the class and directly call the interface from the main class. Let us understand with the previous example :
// Here the interface definition remains same just changing the name for you to understand better     
    @FunctionalInterface
        public interface interfaceWithLambda {    
            public void test(); ---> This is an abstract method
        }
// In Main 
     class mainClass 
         public static void main(String args[]) { 
             interfaceWithLambda inter = () => 
                System.out.println("This is how we implement with lambda"); 
             inter.test(); 
         } 
     } 

Here we can compare both the implementations and see how drastically the code is reduced and readability increased. We have a bunch of interfaces provided to us, which contain one abstract method. We can leverage these interfaces according to our use case.

Predicate<T>

                                    
Predicate is used for validations such as age > 20. So it has a abstract test method which we can use in our lambda. As we know that an interface with only one abstract method can be used for creating a lambda function. 
    interface Predicate
     boolean test(T t); // abstract method test, which we will use for our lambda. 
     }

Let us understand the application of this interface with an example. We want to check in main class, whether the person is above 25 in age. In this usecase we are testing something, hence we can leverage test method of Predicate interface.
class mainClass {
 public static void main(String args[]) { 
    Predicate <Integer> p = age -> age > 25; --> This will return true if age is greater than 25 
//Note : We just implemented test abstract method in the line above where we passed age as a parameter and used lambda to provide implementation for test method of Predicate interface. Now we call this method with our new provided implementation as 
 p.test(26); ----> True will be returned if you print it 
 p.test(22); ----> False will be returned if you print it
        }
    }
Where else can we use this interface? This interface will align to any usecase where we want to test something but also it will be helpful when using filter function in streams. The filter funtion will take a lambda which will implement this interface internally. Let us take a look at another such interface.

Function<T,R>

  • This is also a functional interface
  • Unlike predicate, which returns a boolean , this can return anything after performing an operation on the values passed to it.
Syntax :
interface Function<T,R> { 
     R apply(T t); 
 }
Let us understand this with an example, where we will calculate the length of the String passed to the apply method of this interface.
    interface Function<T,R> { 
     R apply(T t); 
     
     class mainClass { 
         public static void main(String args[]) { 
             Function<String,Integer> fun = str -> str.length(); 
            // Lambda provided implementation for apply method 
            // Beautifully called the apply method
                 int len = fun.apply(s); 
                }
            }
Where else will we use this interface? We can use it in map function in streams.

Consumer<T>


This interface only consumes and returns nothing. Let us look at its syntax :
interface Consumer<T> { 
      void accept(Tt); 
    }
How we will use it in actual code? Let us look at an example.

class mainClass {  public static void main(String args[]) { 
     Consumer<String> c = s -> System.out.println(s); 
     c.accept("whats up"); 
     } 
 }

Supplier<R>

Supplies but consumes nothing. Let us look at how this predefined interface works :
interface Supplier<R> { 
     R get(); 
    }
Example :
class mainClass { 
 public static void main(String [] args) { 
 Supplier<String> s = () -> "Value to return"; 
 s.get(); ---> will return "Value to return" 
     
 }
Next step would be to try out this code in your own IDE and play around with it.

Comments

Popular posts from this blog

My Quarantine "Efforts"

A true relationship is two imperfect people refusing to give up on each other. – Them This blog is on relationships and of course a bit of coding, otherwise it would be stupid to put it here anyways. My girlfriend and I have been having some issues lately regarding the term "Efforts". Now when I put it in front of any of my friends, They have the same reply "Efforts" and when asked what efforts are? … Nothing. I get a supposedly deep answer - Efforts come from within. What does that even mean?. So I tried some stuff to get a response from her. Well for some context we came in relationship on 28 february,2020 and guess when the lockdown started in India. Don't guess, you may as well google it. It was not even a month before the lockdown began and we flew back home. She lives more than 1500km from my state. But you know sometime you just meet the right person and you just know. We knew we had to fight this as we had so much left to say to each ot...

Developing an app with react native and firebase - firestore - Part 1

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. –John F. Woods Let's face it, we are two years into work from home, quarantined from the outside and this makes me wonder that how lucky I am as an engineer to be able to have so many domains open for me to work on, with which I could eventually make money, help others. In other words, it gives me the power to bring a change. I just can't think of a problem where technology cannot help. As soon as I find a problem in minutes my mind starts to work on how it can be solved technically. I think this development is what our college provides us with, to open our technical aspects. Today, I will be talking about react-native and firestore, making app development a little painless and fast. If we are looking to solve a simple everyday problem and want an app to do it for us, an app that is not very complex - react native is the way to go. So,...

What The Hell Is gRPC?

Time is the longest distance between two places. ― Tennessee Williams  If you are a software engineer and you work on websites or any other software which is in high demand by your consumer, but you see that some parts of your application say the products page gets higher demand than any other services you provide at some point of time or let's say you want to loosely couple your application for your application to be developed more easily and flexibly.  These are a few use cases, there are many more. We are seeing a trend in the industry getting more aligned toward following microservices patterns while building the application. The When, Why, Where, and How parts of microservices can be easily found on the internet.  Here I want to talk more about some new technologies which have become an integral part when we talk about microservices. So this blog would be more fruitful for people who know the  When, Why, Where, and How  parts. Today, I will talk a...