Lambda expressions tutorial In java 8




1) Introduction to Lambda expressions?
Lambda expressions are the most valuable addition in java 8. So, we will discuss about them in detail with easy and very simple examples.


2) In short about Lambda expression In java 8 >
  • we can write lambda expression to replace the anonymous inner class.
  • lambda expression make code very neat and clean.
  • lambda expression are very to read. So, they make code more readable.


3) Before learning Lambda expression you must know about >
  • functional interface and
  • anonymous inner class. So, just take a very quick look at both of these.


In short about functional interface. Read about functional interface in detail.


In short about anonymous inner class. Read about anonymous inner class in detail.


Example 1 > How to use Lambda expression


Example 1.1 > Before Java 8 -  Sort String using Using Local class - Without Lambda expression >
import java.util.Arrays;
import java.util.Comparator;
public class SortStringArrayWithoutLambdaExpressionExample {
     
   public static void main(String... args) {
       String[] stringArray = {"ab", "ef", "cd"};
      
       //Create Local class
       class StringSort implements Comparator<String> {
           public int compare(String a, String b) {
                return a.compareTo(b);
          }
       }
    
       //Before Java 8 -  Sort String using Using Local class - Without Lambda expression
       System.out.println("Before Java 8 - Sort StringArray using Using "
        + " > Local class - i.e. Without Lambda expression");
       Arrays.sort(stringArray, new StringSort());
      
       //Display StringArray
         for (String str : stringArray) {
              System.out.print(str + " ");
         }
   }
}
/* Output
Before Java 8 - Sort StringArray using Using > Local class - i.e. Without Lambda expression
ab cd ef
*/


Example 1.2 > Before Java 8 - Sort StringArray using > Anonymous Inner class - i.e. Without Lambda expression >
      Arrays.sort(stringArray, new Comparator<String>() {
                 @Override
                 public int compare(String a, String b) {
                       return a.compareTo(b);
                 }
          });


Example 1.3 > In Java 8 - Sort StringArray using > Lambda expression (Replace Anonymous Inner class with Lambda expression)
import java.util.Arrays;
public class SortStringArrayLambdaExpressionExample2 {
   public static void main(String... args) {
          String[] stringArray = { "ab", "ef", "cd" };
          System.out.println("In Java 8 - Sort StringArray using > Lambda expression");
          Arrays.sort(stringArray, (String a, String b) -> {
                 return a.compareTo(b);
          });

          // Display StringArray
          for (String str : stringArray) {
                 System.out.print(str + " ");
          }
   }
}
/* Output
In Java 8 - Sort StringArray using > Lambda expression
ab cd ef
*/


Example 1.4 > You can shorten up the above lambda expression >
Arrays.sort(stringArray, (a, b) -> {
return a.compareTo(b);
});


Example 1.5 > If there is only Single line in implementation, we can also remove curly braces  (With single line you can also remove return statement) >
Arrays.sort(stringArray, (a, b) -> a.compareTo(b));


Example 1.6 > In Java 8 - Sort StringList using > Lambda expression (using only Single line) >
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SortStringListExpressionExample {
   public static void main(String... args) {
          //Declare StringArray
          String[] stringArray = { "ab", "ef", "cd" };
         
          //Convert String Array to String List
          List<String> stringList = Arrays.asList(stringArray);
      
          //In Java 8 - Sort StringList using > Lambda expression - in one line
          Collections.sort(stringList, (a, b) -> a.compareTo(b));
         
          //Display StringList
          System.out.println(stringList);
   }
}
/* Output
[ab, cd, ef]
*/

Example 2  > How to use Lambda expression - Sum of numbers


Example 2.1  > In Java 8 - Sum of two numbers program using > Lambda expression


@FunctionalInterface
interface CalculatorInterface<A> {
   public abstract A sumMethod(A val1, A val2);
}
public class LambdaExpression_FunctionalInterface_calculatorSum {
   public static void main(String[] args) {
          // Provide implementation (definition) of sumMethod - using Lambda expression
          // A will be type Integer
          CalculatorInterface<Integer> sum = (Integer val1, Integer val2) -> {
                 return val1 + val2;
          };
 
          // Call sumMethod
          Integer result = sum.sumMethod(2, 3);
          System.out.println(result); // 5
   }
}
/* OUTPUT
5
*/


Example 2.2 > You can shorten up the above lambda expression >
CalculatorInterface<Integer> sum = (val1, val2) -> {
   return val1 + val2;
};


Example 2.3 > If there is only Single line in implementation, we can also remove curly braces  (With single line you can also remove return statement) >
CalculatorInterface<Integer> sum = (val1, val2) -> val1 + val2;


Example 3 > How to use Lambda expression - To square a number


Example 3.1 > In Java 8 - square of number program using > Lambda expression


@FunctionalInterface
interface CalculatorInterface<A> {
   A squareMethod(A val);
}
public class LambdaExpression_FunctionalInterface_calculatorSquare {
   public static void main(String[] args) {
          //Provide implementation (definition) of squareMethod using > Lambda expression
          // A will be type Integer
          CalculatorInterface<Integer> square = (val) -> (val * val);
          // Call squareMethod
          Integer result = square.squareMethod(2);
          System.out.println(result); // 4
   }
}
/* Output
4

*/


Example 3.2 > Before Java 8 -  square of number program Using anonymousInnerClass - Without Lambda expression >


CalculatorInterface<Integer> square = new CalculatorInterface() {
         @Override
         public Object squareMethod(Object val) {
             return ((Integer)val * (Integer)val);
         }
};





Example 4 > How to use Lambda expression with threads


Example 4.1 > Before Java 8 - Create thread, Implement Runnable interface using > Anonymous Inner class - i.e. Without Lambda expression
public class WithoutLambdaExpressionThreadExample {
   public static void main(String[] args) {
          System.out.println("1 - Create thread, Implement Runnable interface using > Anonymous inner class");
          // Create thread, Implement Runnable interface using Anonymous inner class
          new Thread(new Runnable() {
                 @Override
                 public void run() {
                       System.out.println("Thread-1");
                 }
          }).start();
   }
}
/*OUTPUT
1 - Create thread, Implement Runnable interface using > Anonymous inner class
Thread-1
*/


Example 4.2  > In Java 8 - Create thread, Implement Runnable interface using > Lambda expression


public class LambdaExpressionThreadExample2 {
   public static void main(String[] args) {
          System.out.println("1 - Implement Runnable interface using > Lambda expression");
          // Implement Runnable interface using > Lambda expression
          new Thread(() -> {
                 System.out.println("Thread-1");
          }).start();
   }
}
/*OUTPUT
1 - Implement Runnable interface using > Lambda expression
Thread-1
*/


Example  > If there is only Single line in implementation, we can also remove curly braces  (With single line you can also remove return statement) >
new Thread(() -> System.out.println("Thread1") ).start();


Example 5 > How to use Lambda expression - String to Integer conversion


Example  > In Java 8 - convert String To Integer using Lambda expression


/*
convert String To Integer using Lambda expression
*/
@FunctionalInterface
interface MyInterface<A, B> {
   A convertStringToIntegerMethod(B stringVal);
}
public class LambdaExpressionExample {
   public static void main(String[] args) {
        // Provide implementation of convertStringToInteger using Lambda expression
        // A will be type Integer
        // B will be of type String
        MyInterface<Integer,String> integerVal= (stringVal) -> Integer.valueOf(stringVal);
        // Call convertStringToInteger
        Integer result = integerVal.convertStringToIntegerMethod("12");
        System.out.println("Integer = "+result); // 12
   }
}
/* OUTPUT
Integer = 12
*/

Labels: Core Java Java 8
eEdit
Must read for you :