Saturday, March 3, 2018

Functions

Functions are exactly same as predicates except that functions can return any type of result but function should return only one value can be any type as per our requirement. To implement functions oracle people introduced function interface in 1.8 version.
Function interface present in java.util.function package.

Functional interface contains only one method i.e., apply()

interface fuction(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(Ramu));
              System.out.println(f.apply(Test));
          }
}
Note

Function is a functional interface and hence it can refer lambda expression.

Difference between predicate and function

Predicate

->To implement conditional checks we should go for predicate.
->Predicate can take one type parameter which represents input argument type. Predicate.
->Predicate interface defines only one method called test().
->public boolean test(T t).
->Predicate can return only boolean value.

Function

->To perform certain operation And to return some result we should go for function.
->Function can take 2 type parameters. First one represent input argument type and Second one represent return type. Function.
->Function interface defines only one method called apply().
->public R apply(T t).
->Function can return any type of value.

Note

Predicates is a boolean valued function and(), or(), negate() are default methods present inside Predicate interface.

Thanks for reading. If you like this post please follow us for more updates about technology related updates.

No comments: