Java8 四大内置核心函数式接口

函数式接口 抽象方法 参数类型 返回类型
消费型接口
Comsumer<T>
void accept(T t); T void
供给型接口
Supplier<T>
T get(); T
函数型接口
Function<T,R>
R apply(T t); T R
断定型接口
Predicate<T>
boolean test(T t); T boolean

这些接口都在java.util.function

import java.util.function.*;

public class Test {
	public static void main(String[] args) {
		//Comsumer消费型接口->输出一句话
		Consumer<String> c=(str)->System.out.println(str);
		c.accept("这是消费型接口Comsumer");
		
		//Supplier供给型接口->从中获取一句话
		Supplier<String> s=()-> "这是消费型接口Supplier";
		System.out.println(s.get());
		
		//Function函数型接口->输入一句话并返回这句话有多少字
		Function<String,Integer> f=(str)->str.length();
		String str="Function函数型接口";
		System.out.println("\""+str+"\"这句话共有"+f.apply(str)+"个字");
		
		//Predicate断定型接口->判断一个数是否为偶数
		Predicate<Integer> p=(x)->x%2==0;
		int x=5;
		System.out.println(x+"为"+(p.test(x)?"偶数":"奇数"));
	}
}
发布了8 篇原创文章 · 获赞 0 · 访问量 170

猜你喜欢

转载自blog.csdn.net/weixin_44231438/article/details/104475332