函数式接口

PPG007 ... 2021-12-28 About 1 min

# 函数式接口

Tips

任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口,可以使用 lambda 表达式。

# 示例

接口:

public interface MyInterface {
    /**
     * 抽象方法
     * @param a 参数
     */
    void show(int a);
}
1
2
3
4
5
6
7

运行:

public static void main(String[] args) {

    MyInterface myInterface = new MyInterface() {
        @Override
        public void show(int a) {
            System.out.println("匿名内部类,参数==> "+a);
        }
    };
    myInterface.show(1);

    MyInterface myInterface1= a -> System.out.println("lambda param is ==> "+a);
    myInterface1.show(2);
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 四大函数式接口

包:java.util.function

# Function

@FunctionalInterface
// 传入T类型,返回R类型
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
1
2
3
4
5
6
7
8
9
10
11

简单使用:

Function<String, String> function=(s -> s+"??");
System.out.println(function.apply("test"));
1
2

# Predicate

Tips

断言型接口,有一个输入参数,返回一个布尔值。

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
1
2
3
4
5
6
7
8
9
10
11

简单使用:

Predicate<Integer> integerPredicate=integer -> integer >100;
System.out.println(integerPredicate.test(21));
System.out.println(integerPredicate.test(210));
1
2
3

# Consumer

Tips

消费型接口,接收一个参数,没有返回值。

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
1
2
3
4
5
6
7
8
9

简单使用:

Consumer<String> stringConsumer= System.out::println;
stringConsumer.accept("test");
1
2

# Supplier

Tips

供给型接口,没有参数,只有返回值。

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}
1
2
3
4
5
6
7
8
9
10

简单使用:

Supplier<String> stringSupplier=()->{
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("t").append("e").append("s").append("t");
    return stringBuilder.toString();
};
System.out.println(stringSupplier.get());
1
2
3
4
5
6

# Stream 流式计算

简单使用:

users.stream()
        .sorted(Comparator.comparingInt(User::getAge))
//                过滤年龄大于等于10
        .filter(user -> user.getAge() >= 10)
//                过滤ID是偶数的
        .filter(user -> user.getId()%2==0)
        .map(user -> user.getName().toUpperCase())
        // 限制输出数量
        .limit(3)
        .forEach(System.out::println);
1
2
3
4
5
6
7
8
9
10

并行计算:

// DoubleStream IntStream ……
long reduce = LongStream.rangeClosed(0L, 100_0000_0000L)
                // 并行流
                .parallel()
                .reduce(0, Long::sum);
1
2
3
4
5
Last update: December 28, 2021 13:51
Contributors: PPG007