Type Inference in Lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

Type Inference states that the data type of any expression. For instance, a method return type or argument type can be understood automatically by the compiler. Types in the argument list can be omitted since java already know the types of the expected parameters for the single abstract method of functional interface.

Syntax

(var1, var2 …) -> { method body }

In the below example, we can sort a String[] array by its last character.

Example

import java.util.Arrays;

public class TypeInferencingLambdaTest {
   public static void main(String[] args) {
      String[] names = {"Raja", "Jai", "Adithya", "Surya", "Chaitanya", "Ravi", "Krishna"};
      Arrays.sort(names, (s1, s2) -> {    // Lambda Expression
         return (s1.charAt(s1.length()-1) - s2.charAt(s2.length()-1));
      });
      for(String str : names) {
         System.out.println(str);
      }
   }
}

Output

Raja
Adithya
Surya
Chaitanya
Krishna
Jai
Ravi
raja
Published on 17-Dec-2019 07:56:57
Advertisements