Saravanan's Corner: Blackberry Dev

Monday, 1 October 2018

Lambda Expressions in Java (from Function Interface)


Lambda Expressions are anonymous methods (methods without names) used to implement a method defined by a functional interface. 

public interface MyGeneric<T> {
public T compute(T t);
}

public interface Greetings {

public String GreetPeople(String str);

}

       public static void main(String args[]) {
Greetings morningGreeting = (str) -> "Good Morning " + str + "!";

Greetings eveningGreeting = (str) -> "Good Evening " + str + "!";

Greetings reverseString = (str) ->{
String result = "";
for(int i = str.length()-1; i >= 0; i--)
result += str.charAt(i);

return result;
};
System.out.println(morningGreeting.GreetPeople("Luis"));

System.out.println(eveningGreeting.GreetPeople("Sara"));

System.out.println(reverseString.GreetPeople("emocleW"));


MyGeneric<String> reverse = (str) -> {
String result = "";
for(int i = str.length()-1; i >= 0; i--)
result += str.charAt(i);

return result;
};
MyGeneric<Integer> factorial = (n) -> {
int result = 1;

for(int i=1; i <= n; i++)
result = i * result;

return result;
};

System.out.println(reverse.compute("sara"));
System.out.println(factorial.compute(40));

}



No comments:

Post a Comment