Functional Interface

Predicate

For filter

1
2
3
4
5
6
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}

Predicate<Integer> p = a -> a == 1;

Function

Covert A to B

1
2
3
4
5
6
7
@FunctionalInterface
public interface Function<T, R> {
// The T is the input argument while R is the return result
R apply(T t);
}

Function<String, Integer> f = Integer::parseInt;

Or accept 2 parameter and output

1
2
3
4
5
6
@FunctionalInterface
public interface BiFunction<T, U, R> {
R apply(T t, U u);
}

BiFunction<Integer, Integer, String> bf = (a, b) -> "" + a + b;

Supplier

Get configuration etc.,

1
2
3
4
5
6
@FunctionalInterface
public interface Supplier<T> {
T get();
}

Supplier<Integer> s = () -> 1;

Consumer

Terminator, do process that doesn’t return

1
2
3
4
5
6
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}

Consumer<Integer> c = System.out::println;

Default Method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@FunctionalInterface
interface RugalFunction<FROM, TO> extends Function<FROM, TO> {

default <OTHER> RugalFunction<OTHER, TO> compose(RugalFunction<? super OTHER, ? extends FROM> before) {
Objects.requireNonNull(before);
System.out.println("Do that first and then do this");
return (OTHER v) -> this.apply(before.apply(v));
}

default <OTHER> RugalFunction<FROM, OTHER> andThen(RugalFunction<? super TO, ? extends OTHER> after) {
Objects.requireNonNull(after);
System.out.println("Do this and then do that");
return (FROM f) -> after.apply(this.apply(f));
}
}


RugalFunction<String, Integer> rf = a -> Integer.parseInt(a);
RugalFunction<String, Float> call = rf.andThen((Integer b) -> b * 1.0F);
System.out.println(call.apply("1"));
/*
--- exec-maven-plugin:1.2.1:exec (default-cli) @ functional ---
Do this and then do that
1.0
*/

Functional Interface
https://rug.al/2018/2018-07-26-functional-interface/
Author
Rugal Bernstein
Posted on
July 26, 2018
Licensed under