java8 function interface --Function / Predict / Consumer

Function

We know that the biggest characteristic Java8 is the functional interface. All marked @FunctionalInterface annotation interface is functional interfaces, specifically, all marked with the annotation interface will be used in the lambda expression.

Interface Description

/**
 * Represents a function that accepts one argument and produces a result.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #apply(Object)}.
 *
 * @param <T> the type of the input to the function
 * @param <R> the type of the result of the function
 *
 * @since 1.8
 */

It found that the above description: the two generic passed Function: T, R representing an input parameter and return type of parameter types. Function will now be described one by one in each interface:

Interface 1: implementing specific interfaces,
R apply (T t);

Example 1: apply using
    // 匿名类的方式实现
    Function<Integer, Integer> version1 = new Function<Integer, Integer>() {
        @Override
        public Integer apply(Integer integer) {
            return integer++;
        }
    };
    int result1 = version1.apply(20);


    // lamda表达式
    Function<Integer, Integer> version2 = integer -> integer++;
    int result2 = version1.apply(20);
    

Interface 2: compose
the default method is a method that receives a function as a parameter, the function performed as a result parameter argument function to the calling function in order to achieve two functions combined.

// compose 方法源码
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
Example 2: compose using
public int compute(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
    return function1.compose(function2).apply(a);
}

// 调用上述方法
test.compute(2, value -> value * 3, value -> value * value) 
// 执行结果: 12 (有源码可以看出先执行before)

Interface 3: andThen
understanding compose methods, we will look at andThen method like to understand, listen name is "Next", andThen method is also receiving a function as a parameter, and compse difference is that the first implementation itself apply method, as a result of the execution parameter to the function parameter.

public interface Function<T, R> {
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
}
Example 3: andThen using
public int compute2(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
    return function1.andThen(function2).apply(a);
}

// 调用上述方法
test.compute2(2, value -> value * 3, value -> value * value) 
// 执行结果 : 36

Reflection: multiple parameters

Function Interface although very simple, but can be seen from Function source, he can only pass a parameter, the actual use certainly can not meet the demand. The following provides a few ideas:

  1. BiFunction can pass two parameters (also provided in other similar Java8 Function)
  2. Solved by package type
  3. void function still can not solve

Because of the parameter "comes Function" function can not necessarily meet the complex and changing business needs, then customize it Function Interface

@FunctionalInterface
    static interface ThiConsumer<T,U,W>{
        void accept(T t, U u, W w);

        default ThiConsumer<T,U,W> andThen(ThiConsumer<? super T,? super U,? super W> consumer){
            return (t, u, w)->{
                accept(t, u, w);
                consumer.accept(t, u, w);
            };
        }
    }

Since then, Function Interface introductions.

Predicate

Interface Description:

/**
 * Represents a predicate (boolean-valued function) of one argument.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #test(Object)}.
 *
 * @param <T> the type of the input to the predicate
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Predicate<T> {

Predicate interface is asserted Its parameters are <T, boolean>, i.e. to a parameter T, return the result of the boolean type. Function with the same specific implementation Predicate is also based on the incoming lambda expression to decide.

No source specific analysis, the main test / and / or / negate method, and a static method of isEqual, using specific examples are as follows:

    private static void testPredict() {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        List<Integer> list = new ArrayList<>();
        for (int i : numbers) {
            list.add(i);
        }
        
        // 三个判断
        Predicate<Integer> p1 = i -> i > 5;
        Predicate<Integer> p2 = i -> i < 20;
        Predicate<Integer> p3 = i -> i % 2 == 0;
        List test = list.stream()
                .filter(p1
                        .and(p2)
//                        .and(Predicate.isEqual(8))
                        .and(p3))
                .collect(Collectors.toList());
        System.out.println(test.toString());
        //print:[6, 8, 10, 12, 14]
    }

Consumer

Interface Description

/**
 * Represents an operation that accepts a single input argument and returns no
 * result. Unlike most other functional interfaces, {@code Consumer} is expected
 * to operate via side-effects.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object)}.
 *
 * @param <T> the type of the input to the operation
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Consumer<T> {

actual use

    NameInfo info = new NameInfo("abc", 123);
    Consumer<NameInfo> consumer = t -> {
        String infoString = t.name + t.age;
        System.out.println("consumer process:" + infoString);
    };
    consumer.accept(info);

Summary:
This paper describes Java8 programming interfaces, as well as three kinds of function interface (FunctionalInterface) jdk provided. Predict and Consumer Function is actually a distortion, so no details.
Question: FunctionalInterface notes is linked to how and lamada expression, function interfaces at compile time and how to deal with back then understand the next?

Guess you like

Origin www.cnblogs.com/NeilZhang/p/11086698.html