Functional interface

Posted by Arenium on Fri, 23 Aug 2019 10:42:40 +0200

1. What is a functional interface?

(1) An interface that contains only one abstract method is called a functional interface.

(2) You can create the object of this interface through Lambda expression. (If a Lambda expression throws a checked exception, the exception needs to be declared on the abstract method of the target interface).

(3) We can use the @Functional Interface annotation on any functional interface to check whether it is a functional interface, and javadoc also contains a declaration that the interface is a functional interface.

2. Custom Functions

Example code 1:

@FunctionalInterface
public interface MyNumber{
    public double getValue();
}

Example code 2: Using generics in functional interfaces

@FunctionalInterface
public interface MyFunc<T>{
    public  T  getValue(T t);
}

3. Transferring Lambda Expressions as Parameters

Sample code:

public String strHandler(String str, MyFunction mf) {
        return mf.getValue(str);
    }
//The Lambda expression is passed as a parameter:
String trimStr = strHandler("\t\t You are a fool.       ", (str) -> str.trim());
String upperStr = strHandler("abcdefg", (str) -> str.toUpperCase());
String newStr = strHandler("I have great prestige", (str) -> str.substring(2, 5));

Transfer Lambda expression as a parameter: In order to transfer Lambda expression as a parameter, the parameter type of receiving Lambda expression must be the type of functional interface compatible with the Lambda expression.

Four Core Functional Interfaces Built in Java

In learning lambda expressions, we know that to use lambda expressions, we need to create a functional interface. It's not too troublesome to use lambda expressions every time. At this time, java has built four core functional interfaces into us.

These interfaces are divided into four main categories:

Consumer (similar to consumer need to pass in parameters with no return value)
Supplier (similar to the fact that the producer does not need to pass in parameters, but has a return value)
Function (both input and return)
Predicate (judgment function, input and return, return true or false)
Their characteristics are as follows:

 

5. Four Interface Examples

Consumer < T >: Consumer interface, void accept (T);

Code example:

@Test
    public void test() {
        happy(10000,(m) -> System.out.println("Big health care spent:"+m));
    }
    public void happy(double  money,Consumer<Double> con) {
        con.accept(money);
    }

2. Supplier < T >: Supply interface, T get();

Sample code:

@Test
    public void test1() {
        List<Integer> numList = getNumList(10, ()->(int)(Math.random()*100 ));
        for (Integer integer : numList) {
            System.out.println(integer);
        }
    }
    
    
    //Requirement: Generate a specified number of integers and put them into the collection
    public List<Integer> getNumList(int num,Supplier<Integer> sup){
            List<Integer> list = new ArrayList<>();
            for(int i=0;i<num;i++) {
                
                Integer n = sup.get();
                list.add(n);
                
            }
            return list;
    }

3. Function < T, R >: Functional Interface, R apply (T);

Sample code:

@Test
    public void  test2() {
        String trimStr=strHandler("\t\t  Hello, world!   ",(str) -> str.trim());
        System.out.println(trimStr);
        
        
        String sumString=strHandler("Helloworld!",(str)->str.substring(2, 4));
        System.out.println(sumString);
    }
    //Requirements: For processing strings
    public  String strHandler(String str,Function<String,String> fun) {
        return fun.apply(str);
    }
    

4. Predicate < T >: assertive interface, Boolean test (T);

Sample code:

    @Test
    public void test3() {
        List<String> list=Arrays.asList("Hello","world","hi","o","123");
        List<String> filterStr = filterStr(list, (str)->str.length()>1);
        for (String string : filterStr) {
            System.out.println(string);
        }
    }
    
    //Requirement: Put qualified strings into a collection
        public List<String> filterStr(List<String> list, Predicate<String> pre){
            List<String> list2=new ArrayList<>();

            for (String str : list) {
                if(pre.test(str)){
                    list2.add(str);
                }
            }
            
            return list2;
        }

 

Topics: Lambda Java