Java : Lambda Expression

What is Lambda expression?

As per Wikipedia, lambda expression also called as anonymous function. It’s a function without name and does not belong to any class. Lambda expression is introduced as part of Java 8 features.

A traditional method or function in java has these main parts.

  • Name
  • Parameter list
  • Body
  • Return type

A lambda expression in java has these main parts.

  • No Name: as this is anonymous function there is no name needed
  • Parameter list
  • Body: this is the main part of the function
  • No return type: you don’t need to mention the return type in lambda’s expression. The java 8+ compiler is able to infer the return type by checking the code.

Program of using lambda expression without any parameters:

@FunctionalInterface
interface NoParamInterface{
    String printHelloWorld();
}

public class NoParamLambdaTest{
    public static void main(String[] args) {
        NoParamInterface noParamInterface= () -> "Hello World";
        System.out.println(noParamInterface.printHelloWorld());
    }
}

Program of using Lambda expression with single parameter:

@FunctionalInterface
interface SingleParam{
    int incrementBy10(int x);
}

public class SingleParamLambdaTest {
    public static void main(String[] args) {
        SingleParam singleParam = (x) -> x+10;
        System.out.println(singleParam.incrementBy10(5));
    }
}

Program of using Lambda expression with multiple parameters:

@FunctionalInterface
interface MultiParam{
    String concat(String x, String y);
}

public class MultiParamLambdaTest {
    public static void main(String[] args) {
        MultiParam multiParam = (x, y) -> x+" "+y;
        System.out.println(multiParam.concat("Hello", "World"));
    }
}

Program of using Lambda expression with Runnable interface:

public class RunnableExample {

    public static void main(String[] args) {
        //Traditional way of implementation
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                int sum=0;
                for(int i=0;i<10;i++)
                    sum +=i;
                System.out.println("Traditional : "+sum);
            }
        };
        new Thread(runnable).start();

        //Implementing using lambda
        Runnable runnable1 = () -> {
            int sum=0;
            for(int i=0;i<10;i++)
                sum +=i;
            System.out.println("Lambda : "+sum);
        };
        new Thread(runnable1).start();

        //Implementing Thread with Lambda
        new Thread(()->{
            int sum=0;
            for(int i=0;i<10;i++)
                sum +=i;
            System.out.println("Thread with Lambda : "+sum);
        }).start();
    }
}

Program of using Lambda expression with Callable interface:

import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class CallableExample {
    public static int[] array = IntStream.range(0,5000).toArray();
    public static int count = IntStream.range(0,5000).sum();

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Callable<Integer> callable1 = () -> {
            int sumOfEven=0;
            for(int i=0;i<array.length;i++){
                if(i%2 == 0)
                    sumOfEven = sumOfEven + i;
            }
            return sumOfEven;
        };

        Callable<Integer> callable2 = () -> {
            int sumOfOdd=0;
            for(int i=0;i<array.length;i++){
                if(i%2 == 1)
                    sumOfOdd = sumOfOdd + i;
            }
            return sumOfOdd;
        };

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        System.out.println("Sum of Even of given range: "+executorService.invokeAny(Arrays.asList(callable1)));
        System.out.println("Sum of Odd of given range: "+executorService.invokeAny(Arrays.asList(callable2)));
        executorService.shutdown();

        System.out.println("Count of the given range is : "+count);
        System.out.println("Sum of Odd and Even is equals to count");
    }
}

Advertisement