Home  >  Article  >  Java  >  What do you need to know about functional interfaces in Java 8?

What do you need to know about functional interfaces in Java 8?

PHPz
PHPzforward
2023-05-04 18:34:071669browse

    Preface

    Java 8 provides many functional interfaces, including Function, Consumer, Supplier, Predicate and so on. They are all located under the java.util.function package.

    What do you need to know about functional interfaces in Java 8?

    Why do you need to know these functional interfaces

    Because these 4 functional interfaces are new important interfaces in Java 8, At the same time, the new Stream features of Java 8 also use these interfaces, so learning them can help us better understand the Stream flow.

    Because this is a functional interface, you can use Lambda expressions to write the implementation logic of the interface. And in the process of learning, you can better understand the ideas of functional programming.

    Function interface

    Description

    The word Function means "function", just like y = f(x) in mathematics, it receives an x ​​parameter. After operating through function f, a result y is returned.

    Function The interface contains four methods:

    • apply(T t): This is Function The main method of the interface, which receives a parameter and returns a result. At the same time, it is also the only abstract method, and the rest have default implementations (the abstract methods of interfaces in Java 8 support default implementations).

    • andThen(Function after): The function is to combine two Function. First execute the current function, then execute the andThen function, and pass the result of the current function as a parameter to the andThen function.

    • compose(Function before): Similarly, when two Function are combined, the compose function will be executed first , then execute the current function, and pass the result of the compose function to the current function as a parameter.

    • identity(): Returns a function that performs identity conversion, that is, returns the input parameter itself.

    Function interface is usually used to convert a value of one type to a value of another type.

    apply method

    // Function 接口的泛型,第一个参数是入参类型,第二个参数是出参类型
    // Function 接口只有一个抽象方法,就是 apply(),下面利用 Lambda 表达式实现这个抽象方法并创建 Function 对象
    Function<Integer, String> function = num -> "GTA" + num;
    // 将5这个参数传递给function,得到返回结果
    String result = function.apply(5);
    System.out.println(result); // 打印:GTA5

    andThen and compose method

    // 定义两个 Function 对象进行相关转换操作
    Function<String, String> upperCase = s -> s.toUpperCase();
    Function<String, String> addPostfix = s -> s + "5";
    // 链式调用,将 gta 这个字符串参数先传递 upperCase 这个函数进行操作,然后将得到的结果传递给 addPostfix 函数进行操作,得到返回结果
    String str = upperCase.andThen(addPostfix).apply("gta");
    System.out.println(str); // 打印:GTA5

    identify method

    identity method returns a function that performs identity conversion , this function returns the input parameters unchanged. For example:

    Function<String, String> identity = Function.identity();
    String result = identity.apply("hello"); // result is "hello"

    Consumer interface

    Explanation

    Consumer means "consumer". It consumes the input parameters and does not return the result. for you.

    Consumer interface contains two methods:

    • accept(T t): This method accepts a parameter and performs some operations.

    • andThen(Consumer after): In the same way, combine two Consumers and consume them one after another.

    accept method

    Consumer interface is usually used to consume a parameter and then perform some operations. For example:

    // Consumer 接口,泛型参数是入参类型,接受一个参数,并不返回结果,相当于消费了这个参数
    Consumer<String> consumer = s -> System.out.println(s);
    consumer.accept("我输入什么就打印什么"); // 打印:我输入什么就打印什么

    andThen method

    combines two Consumers:

    Consumer<String> first = s -> System.out.println(s + 5);
    Consumer<String> second = s -> System.out.println(s + 6);
    // 先执行 first 这个 Consumer,接着执行 second 这个 Consumer
    Consumer<String> combination = first.andThen(second);
    combination.accept("GTA"); // 打印:GTA5 GTA6

    Supplier interface

    Supplier interface only defines one

    get() Method, this method does not accept any parameters and returns a result.

    Supplier This word means "supplier". It gives me the feeling that it is a producer, without parameters, it directly produces something for you.

    The Supplier interface is usually used to generate a value. For example:

    // Supplier 接口,泛型参数是出参类型,不接受参数,但是会提供结果,相当于生产了某个东西
    Supplier<String> supplier = () -> "提供一个我随便打的字符串给调用方";
    String text = supplier.get();
    System.out.println(text); // 打印:提供一个我随便打的字符串给调用方

    Predicate interface

    Description

    The word Predicate means "prophecy, prediction, predicate, predicate", which is used for prediction and judgment.

    Predicate The interface contains four methods:

    • test(T t): This method accepts one parameter and returns A Boolean value.

    • and(Predicate other): Combine with another Predicate to implement logical and operations.

    • negate(): Combined with another Predicate to implement logical non- operations.

    • or(Predicate other): Combine with another Predicate to implement logical or operations.

    test method

    The Predicate interface is usually used to test whether a condition is true. For example:

    // Predicate 接口,泛型参数是入参类型,返回布尔值
    Predicate<String> predicate = s -> s.contains("god23bin");
    boolean flag = predicate.test("god23bin能给你带来收获吗?");
    System.out.println("god23bin能给你带来收获吗?" + flag); // 打印:god23bin能给你带来收获吗?true

    and method

    For the convenience of demonstration, two Predicates are prepared here:

    Predicate<String> startsWithA = (str) -> str.startsWith("A"); // 如果传入的字符串是A开头,则返回 true
    Predicate<String> endsWithZ = (str) -> str.endsWith("Z"); // 如果传入的字符串是Z结尾,则返回 true

    Use and to combine,

    and operations:

    Predicate<String> startsWithAAndEndsWithZ = startsWithA.and(endsWithZ);
    System.out.println(startsWithAAndEndsWithZ.test("ABCDEFZ")); // true
    System.out.println(startsWithAAndEndsWithZ.test("BCDEFGH")); // false

    negate method

    Use negate for combination,

    non-operation:

    Predicate<String> notStartsWithA = startsWithA.negate();
    System.out.println(notStartsWithA.test("ABCDEF")); // false
    System.out.println(notStartsWithA.test("BCDEFGH")); // true

    or method

    Use or for combination,

    Or Operation:

    Predicate<String> startsWithAOrEndsWithZ = startsWithA.or(endsWithZ);
    System.out.println(startsWithAOrEndsWithZ.test("ABCDEF")); // true
    System.out.println(startsWithAOrEndsWithZ.test("BCDEFGH")); // false

    What are the applications of these interfaces?

    These functional interfaces are applied in the Stream stream. Of course, when you have similar needs, you can also apply these interfaces yourself. Let’s talk about the applications in Stream flow.

    Function 接口:例如 map 方法,map 方法就是将一个类型的值转换为另一个类型的值。

    // map 方法,将 T 类型的值转换成 R 类型的值
    // R 是返回的 Stream 流的元素类型,T 是原先 Stream 流的元素类型
    <R> Stream<R> map(Function<? super T, ? extends R> mapper);

    Consumer 接口:例如 forEach 方法

    // forEach 方法,遍历 Stream 流中的元素,T 类型是 Stream 流的元素类型
    void forEach(Consumer<? super T> action);

    Supplier 接口:例如 generate 方法

    // 生成一个无限长度的 Stream 流
    public static<T> Stream<T> generate(Supplier<T> s) {
        Objects.requireNonNull(s);
        return StreamSupport.stream(
            new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false);
    }

    Predicate 接口:例如 filter 方法,使用 Predicate 进行过滤操作。

    // 过滤出 Stream 流中,判断结果为 true 的元素
    Stream<T> filter(Predicate<? super T> predicate);

    The above is the detailed content of What do you need to know about functional interfaces in Java 8?. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete