The functional interface of Java

Source: Internet
Author: User

Functional Interface Overview: There is only one abstract method in the interface

The following may be very abstract, can not understand, at least in my opinion, the individual excuses are useless, with the bottom of the stream stream to use in order to have the effect

  • Functional interface, which is the interface for functional programming scenarios. Functional programming in Java is a lambda, so functional interfaces are
    To the interface that is used for lambda. Lambda in Java can only be deduced smoothly if there is only one abstract method in the interface.

    Note: "Syntax sugar" refers to the use of more convenient, but the principle of the same code syntax. For example, the For-each syntax used when traversing a collection, in fact
    The underlying implementation principle is still an iterator, which is the "syntactic sugar". In terms of application, lambda in Java can be treated as an anonymous internal
    The "syntactic sugar" of the class, but the two are different in principle.

  • Format:
    1. Just make sure that there is only one abstract method in the interface:

       修饰符 interface 接口名称 {    public abstract 返回值类型 方法名称(可选参数信息);    // 其他非抽象方法内容 }
    2. @FunctionalInterface annotations

      Similar to the @override annotation, Java 8 introduces a new annotation specifically for the functional interface: @FunctionalInterface. The note
      The solution can be used on the definition of an interface, and once the annotation is used to define the interface, the compiler will force the check to see if the interface is really and only an abstract method, otherwise it will be an error. Need to note
      This means that even if the annotation is not used, as long as the definition of the functional interface is satisfied, this is still a functional interface, which is used in the same way.

    3. Custom Function Interface (written previously, this does not repeat)

      Package com.wzlove.function;

      /**
      • Custom Function interface
      • Using @functionalinterface can indicate that the interface is a functional interface, but no, if there is only one abstract method in the interface, this interface is also a function interface
      • That is, the functional interface does not exist as an annotation.
        */
        @FunctionalInterface
        Public interface Myfunctionalinterface {

        public abstract void Show ();
        }

Lambda expression: (argument list)->{code}LAMBDA expression (previous article said, not detailed)

Custom function interface with parameters and return values

    @FunctionalInterface    public interface Sumable {        int sum(int a, int b);    }
Some functional interfaces after JDK1.8 supplier production data function interface

The purpose is to produce data.

It doesn't seem to work at the moment, but it seems to have something to do with the stream flow of jdk8. For a small example

    package com.wzlove.supplier;        import java.util.function.Supplier;        /**     * 使用supplier函数式接口求数组的最大值     */    public class ArrMaxValue {            public static int getMaxValue(Supplier<Integer> sup){            return sup.get();        }            public static void main(String[] args) {            // 创建数组            int[] arr = {100,20,50,30,99,101,-50};                int maxValue = getMaxValue(()->{                int max = arr[0];                for (int i : arr) {                    if(i > max){                        max = i;                    }                }                return max;            });                System.out.println("数组中的最大值为:" + maxValue);        }        }
Consumer consumption data Function interface

This method is used to consume data, how to consume, and to define the consumption rules themselves.

Java.util.function.Supplier

package com.wzlove.comsumer;import java.util.function.Consumer;/** * 使用Consumer函数式接口实现格式化输出 */public class ConsumerDemo2 {    public static void printInfo(String[] strArr, Consumer<String> con1, Consumer<String> con2){        for (int i = 0; i < strArr.length; i++) {            con1.andThen(con2).accept(strArr[i]);        }    }    public static void main(String[] args) {        String[] strArr = {"迪丽热巴,女","郑爽,女","杨紫,女"};        printInfo(strArr,(message)->{            System.out.print("姓名:" + message.split(",")[0] + "。  ");        },(message)->{            System.out.println("性别:" + message.split(",")[1] + "。");        });    }}
predicate Judgment function interface

The predicate interface contains an abstract method: Boolean Test (T-t). Scenarios for conditional judgment

Default method:

    • Default predicate
    • Default predicate
    • Default predicate

      Package com.wzlove.functionalinterface.predicate;

      Import java.util.ArrayList;
      Import Java.util.function.Predicate;

      /**
      • */
        public class PredicateDemo2 {

        /**
        • Checks if the elements in the array meet the requirements, satisfies the requirements and joins the list and returns
        • @param arr needs to determine the array
        • @param pre1 1 To determine whether gender is female
        • @param Pre2 Judgment Interface 2, determine whether the name length is greater than 2
        • @return Collection
          */
          public static ArrayList

        public static void Main (string[] args) {
        Create an array
        String[] arr = {"Dirigeba, female", "Yang Yang, male", "Li Xire, female", "Zhengshuang, Female"};

          // 调用方法(Lambda表达式可以简化)  ArrayList<String> list = checkStar(arr,(str)->{      return str.split(",")[1].equals("女");  },(str)->{      return str.split(",")[0].length() > 2;  });  // 遍历集合  for (String elem : list) {      System.out.print(elem + "   ");  }

        }

      }

Function-type conversion functional interface

The main abstract method in the Function interface is: R apply (T-t), which gets the result of type R based on the parameter of type T.

The Function interface has a default Andthen method for combining operations.

  Package Com.wzlove.functionalinterface.function;import java.util.function.function;/** * */public class FunctionDemo2 {/** * Splits a string, obtains the second element, converts the data to int,int data plus 100, and then converts int to String * @param str converted data * @param f       UN1 string-String * @param fun2 string, Integer * @param fun3 integer-String * @return Last String */public static string convert (String str, function<string,string& Gt FUN1, function<string, integer> fun2, Function<integer,    String> fun3) {return Fun1.andthen (fun2). Andthen (FUN3). Apply (str); } public static void Main (string[] args) {String str = convert ("Dirigeba, 23°c", (s)->{return S.split (",        ") [1];        }, (s)->{return Integer.parseint (s) + 100;        }, (s)->{return string.valueof (s);        });    System.out.println (str); }}

Functional interface of Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.