Posts

Predefined Functional Interface - Function-Java

Predefined Functional Interface Functions are exactly same as predicates except that functions can return any type of result but function should (can) return only one value and that value can be any type as per our requirement. To implement functions oracle people introduced Function interface in 1.8version. Function interface present in Java.util.function package. Functional interface contains only one method i.e., apply() interface function(T,R) { public R apply(T t); } Assignment: Write a function to find length of given input string. Ex: import Java.util.function.*; class Test { public static void main(String[] args) { Function<String, Integer> f = s ->s.length(); System.out.println(f.apply("Hello MS")); System.out.println(f.apply("JDK8")); } } Note: Function is a functional interface and hence it can refer lambda expression. Differences between predicate and function Predicate Function ...

Predefined Functional Interface - Predicate -Java

Predefined Functional Interface Predicate A predicate is a function with a single argument and returns boolean value. To implement predicate functions in Java, Oracle people introduced Predicate interface in 1.8 version (i.e.,Predicate<T>). Predicate interface present in Java.util.function package. It’s a functional interface and it contains only one method i.e., test() Ex: interface Predicate<T> { public boolean test(T t); } As predicate is a functional interface and hence it can refers lambda expression Ex:1 Write a predicate to check whether the given integer is greater than 10 or not. Ex: OPTION 1: public boolean test(Integer I) { if (I >10) { return true; } else { return false; } } OPTION 2: (Integer I) ->{ if(I > 10) return true; else return false; } OPTION 3: I ->(I>10); Predicate<Integer> p = I ->(I >10); System.out.println (p.test(100)); true System.out.print...

Lambda ( λ ) Expression -Java

Lambda ( λ ) Expression ☀ Lambda calculus is a big change in mathematical world which has been introduced in 1930. Because of benefits of Lambda calculus slowly this concepts started using in programming world. “LISP” is the first programming which uses Lambda Expression. ☀ The other languages which uses lambda expressions are:  C#.Net  C Objective  C  C++  Python  Ruby etc. and finally in Java also. ☀ The Main Objective of Lambda Expression is to bring benefits of functional programming into Java. What is Lambda Expression (λ): Lambda Expression is just an anonymous (nameless) function. That means the function which doesn’t have the name, return type and access modifiers. Lambda Expression also known as anonymous functions or closures. Ex: 1 Normal Lambda Expression (λ) public void m1() { sop(“hello”); } () -> { sop(“hello”); } () ->{ sop(“hello”); } () -> sop(“hell...