package com.nikolas.java8;
import java.util.function.Function;
/**
* @FunctionalInterface
* 该注解的接口是函数式接口
* 标注了该注解的接口都将能用在lambda表达式上。
*/
public class FunctionDemo {
/***
* R apply(T t);
* 输入参数T
* 返回结果R
* R = f(t) = t + 1
*/
public static Object apply(Integer argument){
/**
* 定义一个函数f(t) = t + 1;
*/
Function<Integer,Integer> function = t->t+1;
/**
* 输入函数的入参argument 返回函数的值
*/
return function.apply(argument);
}
/**
* 定义:f1(X) = x+1
* 定义:f2(x) = x*x
* f3(X) = f1(X).compose(f2(X))
* compose 将f2(x)的运算结果作为f1(x)的入参
* f3(X) = f1(f2(x)) = (x*x)+1;
* @param num 输入的参数
*/
public static void compose(Long num){
Function<Integer,Long> function1 = t ->Long.valueOf(t+1);
Function<Long,Integer> function2 = t -> t.intValue()*t.intValue();
Function<Long,Long> function3 = function1.compose(function2);
System.out.println("测试3:"+function3.apply(num));
}
/**
* 定义:f1(X) = x+1
* 定义:f2(x) = x*x
* f3(X) = f1(X).andThen(f2(X))
* andThen 将f1(x)的运算结果作为f2(x)的入参
* f3(X) = f2(f1(x)) = (X+1)*(x+1);
* @param num 输入的参数
*/
public static void andThen(Integer num){
Function<Integer,Long> function1 = t ->Long.valueOf(t+1);
Function<Long,Integer> function2 = t -> t.intValue()*t.intValue();
Function<Integer,Integer> function3 = function1.andThen(function2);
System.out.println("测试4:"+function3.apply(num));
}
public static void main(String[] args) {
//测试1
System.out.println("测试1:"+FunctionDemo.apply(8));
//测试3
FunctionDemo.compose(3L);
//测试4
FunctionDemo.andThen(3);
}
}
文章评论