closeUpLambda

java.util.function Inerfaces



java.util.function is a package which contain multiple functional Interfaces.

It is an Functional Interface used to assignment for lambda expression or method.

For more information on Lambda

https://linuxdeb.com/tut/lambda-expression/

e.g

import java.util.function.Function;
public class UTest {
public static void main(String[] args) {
Function<Integer, Integer> add5 = x -> x+5;
// simplified lambda
Function<Integer, Integer> add2 = (x) -> {return x+2;};
System.out.println(add5.apply(34));
System.out.println(add2.apply(23));

}
}

why we use functional programming

we use Lambda to shorten our code. The Lambda function act as an anonymous function.
To hold the reference of function or lambda expression.
e.g

public class Fun {
public static Integer add5(Integer x) { return x + 5; }
}
Function<Integer,Integer> addRef = Fun::add5;

so addRef contains the reference of Fun class add5 method

public class Fun {
public Integer add5(Integer x) { return 10 + 5; }
}
Fun f = new Fun();
Function<Integer,Integer> addRef = f::add5;
System.out.println(addRef.apply(23));

Here the addRef just contain the refrence of fun object method.
The output of this code will be 15

Java uses different functional interfaces for different function varieties.
Function<T,R> is a functional interface for any unary function. I.e It take one input and give one output

BiFunction<T,U,R> takes two argumetns and produces a result
IntFunction<R>

Predicate<T> Reresent a predicate (voolean-valued functionf) of one argument.
BiPredicate<T,U> take two value and returns a boolean
Supplier<T> Supplies result
Consumer<T> accept single argument and returns no result
UnaryOperator<T> take one input, return same type as of input
BinaryOperator<T> take two argument of same type and return value same type as of input

There are also primitive version of this interface to avoid cost of boxing and unboxing of these interfaces.

import java.util.function.*;

public class Main {

public static void main(String[] args) {
System.out.println("Hello World!");
Function<Integer, Integer> add5 = x -> x+5;
// simplified lambda
Function<Integer, Integer> add2 = (x) -> {return x+2;};
System.out.println(add5.apply(34));
System.out.println(add2.apply(23));
BiFunction<String, String, String> concat = (x,y) -> {return x+y;};
System.out.println(concat.apply("Hi", " Tom"));
Consumer<String> printName = (x) -> {System.out.println(x);};
printName.accept("World");
Predicate<Integer> div5 = (x) -> {if(x%5 == 0)return true;
else {return true;}
};

System.out.println(div5.test(45));

Supplier<String> getName = ()-> {return "Name";};
System.out.println(getName.get());

UnaryOperator<Integer> inc = x -> {return x++;};
System.out.println(inc.apply(4));
BinaryOperator<Integer> addBin = (x,y) -> {return x+y;};
System.out.println(addBin.apply(4,5));


}
}

Image by Hartmut Jaster from Pixabay