Java

Java functional interface. Lambda, Consumer, Supplier, Predicate.

Functional interface – an interface with single abstract method. Optionally marked with @FunctionalInterface annotation.

 
@FunctionalInterface
interface MyFunction {
    Integer square(Integer x);
}

MyFunction func = x -> x * x;
System.out.println(func.square(7));

 

Lambda – functional interface with a method, which receives and returns value

Function<Integer, Integer> square = num -> num * num;
System.out.println(square.apply(4));

 

Supplier – function, which does not receive value, but returns one. Mostly used for lazy value generation.

Supplier<Integer> sup = () -> {
            return 5;
        };
System.out.println(sup.get());

 

Consumer – function, which receive value, but does not return. Mostly used for side effect functionality.

Consumer<Integer> con = (v) -> {
            System.out.println(v * v);
        };
con.accept(5);

 

Predicate – function, which receives any type of value and returns only boolean value

Predicate<Integer> isPositive = x-> x>0;
System.out.println(isPositive.test(5));

About Danas Tarnauskas