java tutorial: java 8 Lambda built-in functional interfaces
November 3, 2020
Functional interface is a new feature introduced by Java 8. It is an interface that contains only one abstract method.
Java 8 provides four built-in core functional interfaces.
This article introduces you to these functional interfaces and usage examples.
Name | Parameter | Return | Method |
---|---|---|---|
Function<T, R> | T | R | R apply(T t); |
Supplier<T> | T | void | T get(); |
Consumer<T> | T | void | void accept(T t); |
Predicate<T> | T | boolean | boolean test(T t); |
Examples
Function<T, R> : R apply(T t)
Input a T
type parameter and return an R
type value
/**
* Function FunctionalInterface Test
*/
@Test
public void testFunctionInterface() {
Function<String, String> f = (x) -> {
return x.substring(3, 10);
};
String s = f.apply("Hi, Lambda!");
System.out.println(s);
}
Supplier<T> : T get()
No input, return a value of type T
/**
* Supplier FunctionalInterface Test
*/
@Test
public void testSupplier() {
Supplier<Integer> s = () -> {
Random random = new Random();
Integer i = random.nextInt(100);
return i;
};
Integer res = s.get();
System.out.println(res);
}
Consumer<T> : void accept(T t)
Input a T
type parameter and process, no return value
/**
* Consumer FunctionalInterface Test
*/
@Test
public void testConsumer() {
Consumer<Integer> c = (i) -> {
int s = 0;
for (int j = 0; j < i; j++) {
s += j;
}
System.out.println(s);
};
c.accept(10);
}
Predicate<T> : boolean test(T t)
Input a T
type parameter, process and make logical judgment and return true
or false
/**
* Predicate FunctionalInterface Test
*/
@Test
public void testPredicate() {
Predicate<String> p = (x) -> {
return x.length() > 5;
};
boolean b = p.test("Hello Lambda.");
System.out.println(b);
}
In addition to the four types of functional interfaces mentioned above, some interfaces are also provided for us to use.
Other functional interfaces
Name | Parameter | Return | Method |
---|---|---|---|
BiFunction<T, U, R> | T, U | R | R apply(T t, U u); |
BiConsumer<T, U> | T, U | void | void accept(T t, U u) |
BinaryOperator<T> (BiFunction Subinterface) | T, T | T | T apply(T t1, T t1); |
UnaryOperator<T> (Function Subinterface) | T | T | T apply(T t); |
ToIntFunction<T> ToLongFunction<T> ToDoubleFunction<T> | T | int long double | int applyAsInt(T value); long applyAsLong(T value); double applyAsDouble(T value); |
IntFunction<R> LongFunction<R> DoubleFunction<R> | int long double | R | R apply(int value); R apply(long value); R apply(double value); |