Friday, May 1, 2020

Java 8 Functional Interface


A Functional interfaces have single functionality to exhibit. Just like compareTo function is used for comparison purpose.

1. Function<T, R>

Function takes one argument of type T and Returns one argument of type R.

Here,
T -> Type of input to the function.
R -> Type of output/result of the function.

Example: 

Function<String, Integer> getStringLengthFunction = x->x.length()
Integer length = getStringLengthFunction.apply("abhay");
System.out.println(length);

The output will be: 5

2. Chaining Function <T, R>


We can chain multiple functions:

Example: 

Function<String, Integer> getStringLengthFunction = x->x.length();
Function<Integer,Integer> multiplyFunction = x->x*2;

Integer value = getStringLengthFunction.andThen(multiplyFunction).apply("abhay");
System.out.println(value);

The output will be: 10

3. BiPredicate Function <T, R>


The BiPredicate function takes two arguments as input and returns boolean value. Meaning you can input two arguments, process it and return the result in boolean.

Example:

BiPredicate <String,Integer> validateLength = (x,y) -> {
          return x.length() == y;
};

boolean isCorrect = validateLength.test("abhay",5);
System.out.println(isCorrect);

isCorrect = validateLength.test("abhay",10);
System.out.println(isCorrect);

The output will be: 
true
false

4. Consumer <T>


The Consumer function takes one argument as input and doesn't return anything.

Example:

Consumer <String> value = x ->{
          System.out.println("The value is: "+x);
};

value.accept("abhay");

The output will be: The value is: abhay

5. Supplier <R>


The Supplier is opposite of the Consumer, it takes nothing but returns object.

Example:

Supplier<LocalDateTime> s = () -> LocalDateTime.now();
LocalDateTime localDateTime = s.get();
System.out.println(localDateTime);

The output will be: 2020-05-02T10:26:38.454

No comments:

Post a Comment

Terraform Cheat Sheet [WIP]

Installing Terraform