Difference between revisions of "Kava Lambda Expressions"
From MyWiki
| (3 intermediate revisions 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 5: | Line 6: | ||
} | } | ||
</source> | </source> | ||
| − | Example1<br> | + | Example1 - Numeric Test<br> |
<source lang="java"> | <source lang="java"> | ||
interface NumericTest { | interface NumericTest { | ||
| 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")); }