java8 lambda 使用 与 functional interface 与 function 类

来源:互联网 发布:国内外大数据现状分析 编辑:程序博客网 时间:2024/06/06 14:27

java 8 中的 function 类 属于 lamda表达式的一种,它定义好了一些接口,可以直接来调用,比较方便。

若不使用 java 自带的 function 类,在定义好接口后,再用 lamda 表达式来表达 functional interface 中的函数。


举例:

import java.util.function.Function;import java.util.function.Predicate;public class HelloWorld {// functional interface@FunctionalInterfaceinterface StringMapper{int map(String str);}public static void main(String[] args){StringMapper mapper=(String str)->str.length();System.out.println(mapper.map("chen"));// Function <T, R>Function<Integer,Integer> square1=(x)->x*x;System.out.println(square1.apply(5));// chaining three functionsFunction<Long, Long> chainedFunction = ((Function<Long, Long>)(x -> x * x)).andThen(x -> x + 1).andThen(x -> x * x);System.out.println(chainedFunction.apply(3L));// predictatesPredicate<Integer> greaterThanTen=x->x>10;System.out.println(greaterThanTen.test(15));}}



输出:

4

25
100
true

原创粉丝点击