Difference between revisions of "Kava Lambda Expressions"

From MyWiki
Jump to: navigation, search
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
 +
Reference - https://www.freecodecamp.org/news/learn-these-4-things-and-working-with-lambda-expressions-b0ab36e0fffc/<br>
 
Functional Interface<br>
 
Functional Interface<br>
 
<source lang="java">
 
<source lang="java">
Line 20: Line 21:
 
// Output: true
 
// Output: true
 
System.out.println(isNegative.computeTest(-5));
 
System.out.println(isNegative.computeTest(-5));
 +
}
 +
</source>
 +
Example2 - Greeting Lambda<br>
 +
<source lang="java">
 +
interface MyGreeting {
 +
String processName(String str);
 +
}
 +
 +
public static void main(String args[]) {
 +
MyGreeting morningGreeting = (str) -> "Good Morning " + str + "!";
 +
MyGreeting eveningGreeting = (str) -> "Good Evening " + str + "!";
 +
 
 +
  // Output: Good Morning Luis!
 +
System.out.println(morningGreeting.processName("Luis"));
 +
 +
// Output: Good Evening Jessica!
 +
System.out.println(eveningGreeting.processName("Jessica"));
 
}
 
}
 
</source>
 
</source>

Latest revision as of 21:00, 10 April 2020

Reference - https://www.freecodecamp.org/news/learn-these-4-things-and-working-with-lambda-expressions-b0ab36e0fffc/
Functional Interface

interface MyName{
  String computeName(String str);
}

Example1 - Numeric Test

interface NumericTest {
	boolean computeTest(int n); 
}
 
public static void main(String args[]) {
	NumericTest isEven = (n) -> (n % 2) == 0;
	NumericTest isNegative = (n) -> (n < 0);
 
	// Output: false
	System.out.println(isEven.computeTest(5));
 
	// Output: true
	System.out.println(isNegative.computeTest(-5));
}

Example2 - Greeting Lambda

interface MyGreeting {
	String processName(String str);
}
 
public static void main(String args[]) {
	MyGreeting morningGreeting = (str) -> "Good Morning " + str + "!";
	MyGreeting eveningGreeting = (str) -> "Good Evening " + str + "!";
 
  	// Output: Good Morning Luis! 
	System.out.println(morningGreeting.processName("Luis"));
 
	// Output: Good Evening Jessica!
	System.out.println(eveningGreeting.processName("Jessica"));	
}