java tutorial: java 8 Lambda built-in functional interfaces

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.

NameParameterReturnMethod
Function<T, R>TRR apply(T t);
Supplier<T>TvoidT get();
Consumer<T>Tvoidvoid accept(T t);
Predicate<T>Tbooleanboolean 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

NameParameterReturnMethod
BiFunction<T, U, R>T, URR apply(T t, U u);
BiConsumer<T, U>T, Uvoidvoid accept(T t, U u)
BinaryOperator<T>
(BiFunction Subinterface)
T, TTT apply(T t1, T t1);
UnaryOperator<T>
(Function Subinterface)
TTT apply(T t);
ToIntFunction<T>
ToLongFunction<T>
ToDoubleFunction<T>
Tint
long
double
int applyAsInt(T value);
long applyAsLong(T value);
double applyAsDouble(T value);
IntFunction<R>
LongFunction<R>
DoubleFunction<R>
int
long
double
RR apply(int value);
R apply(long value);
R apply(double value);

Add a Comment

Your email address will not be published. Required fields are marked *