Lambda语法实际上简化为了方法引用,但是Lambda核心在于函数式接口,而函数式接口的核心就是只有一个方法。函数式编程里面只需要有四类接口(包:java.util.function):(见下图)
1. 功能型函数式接口:(输入一个数据,经过处理后输出一个数据)
public interface Function<T,R>{public R apply(T t);}
代码示例:功能型函数式接口 (例:String.valueOf())
package cn.edu.www;
import java.util.function.Function;
public class TestDemo {
public static void main(String[] args) {
Function<Integer,String> p=String::valueOf;
System.out.println(p.apply(20).length());
}
}
运行结果:
2
2. 供给型函数式接口
public interface Supplier<T>{public T get();}
代码示例:供给型函数式接口(”hello”.toUpperCase())
package cn.edu.www;
import java.util.function.Supplier;
public class TestDemo {
public static void main(String[] args) {
Supplier<String> p="world"::toUpperCase;
System.out.println(p.get());
}
}
运行结果:
WORLD
3. 消费型函数式接口
public interface Consumer<T>{public void accept(T t);}
代码示例:消费型函数式接口(System.out.println();)
package cn.edu.www;
import java.util.function.Consumer;
public class TestDemo {
public static void main(String[] args) {
Consumer<String> p=System.out::println;
p.accept("hello world!");
}
}
运行结果:
hello world!
4. 断言型函数式接口
public interface Predicate<T>{public boolean test(T t);}
代码示例:断言型函数式接口(startsWith)
package cn.edu.www;
import java.util.function.Predicate;
public class TestDemo {
public static void main(String[] args) {
Predicate<String> p="##hello"::startsWith;
System.out.println(p.test("##"));
}
}
运行结果:
true
如果要进行复杂的Lambda运算,就需要利用这类的函数式接口进行操作。