Java 8 - Functional interfaces

2018-03-06  本文已影响0人  YoungJadeStone

今天聊聊一些Functional interfaces,也就是一些函数式接口。本文介绍从Java 1.8开始的新的Functional interfaces。

在Java 1.8以前就有Functional interfaces,比如java.lang.Runnable,java.util.Comparator,etc。在1.8里,又有一些新的interface被引入,它们都在package java.util.function下面。

官方文档里面对java.util.function的描写:

Functional interfaces provide target types for lambda expressions and method references. Each functional interface has a single abstract method, called the functional method for that functional interface, to which the lambda expression's parameter and return types are matched or adapted. Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context.

java.util.function里面常用的interface:

Predicate

Predicate代表的是有判断功能的function。

public class Test {  
    public static void main(String[] args) {  
        String name1 = "";  
        String name2 = "012345";  
        System.out.println("Result of the 1st example: " + validInput(name1, input -> input.isEmpty()));  
        System.out.println("Result of the 2nd example: " + validInput(name2, input -> input.length() > 3));  
    }  
      
    public static boolean validInput(String name, Predicate<String> criteria) {  
        return criteria.test(name);  
    }  
}  

返回结果:

Result of the 1st example: true
Result of the 2nd example: true

Predicate的其他method包括:

Function

public class Test {  
    public static void main(String[] args) {  
        int number = 12345;  
        number = validInput(number, x -> {
            x = x / 100;
            System.out.println("number is " + x);
            return x;
        });  
        System.out.println("current number is " + number);
    }  
      
    public static int validInput(int number, Function<Integer,Integer> function) {  
        return function.apply(number);  
    }  
}  

返回结果:

number is 123
current number is 123

Consumer

public class Test {  
    public static void main(String[] args) {  
        int number = 12345;  
        validInput(number, x -> {
            System.out.println("number is " + x / 100);
            return;
        });  
        System.out.println("current number is " + number);
    }  
      
    public static void validInput(int number, Consumer<Integer> function) {  
        function.accept(number);  
    }  
}  

返回结果:

number is 123
current number is 12345

To be continued...

Good Material

http://www.runoob.com/java/java8-functional-interfaces.html

上一篇下一篇

猜你喜欢

热点阅读