interface Inter{
public void demo(int a);
}
public class Test1{
public static void main(String[] args) {
Inter i = a -> {
//根据接口中的参数类型,推断这里a的类型
System.out.println( a % 2 == 0 ? "偶数" :"奇数");
};
}
}
如果只有一个参数是可以省略参数外的小括号,如果返回值只有一条语句可以省略返回值外的大括号
//只有一个参数可以省略掉参数外的小括号
Inter i = a -> {
System.out.println( a % 2 == 0 ? "偶数" :"奇数");
};
//方法返回值只有一条语句,省略大括号
Comparator<Integer> com = (o1,o2) -> o1 - o2;
@FunctionalInterface //定义此接口为函数式接口
interface Inter{
public void demo();
}
public class Test1{
public static void main(String[] args) {
//调用method方法,并将函数式接口作为参数
method( () -> {
System.out.println(
"函数式接口作为参数"
);
});
}
public static void method(Inter inter){
inter.demo();
}
}
函数式接口作为方法上的返回值
@FunctionalInterface
interface Inter{
public void demo();
}
public class Test1{
public static Inter method2(){
return () -> {
System.out.println("函数式接口作为方法返回值");
};
}
@FunctionalInterface
public interface Supplier<T> {
T get();
}
//supplier接口演示
public class Test1{
public static void main(String[] args) {
String s = demo(()->"123");
System.out.println(s);
}
//创建方法,参数为Supplier对象
public static <T>T demo(Supplier<T> supplier){
return supplier.get();
}
}
Consumer接口,它是一个消费者接口,其中有一个accept方法,接收任意类型的对象
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
//Consumer接口演示
public class Test1{
public static void main(String[] args) {
demo(100,(integer)->{});
}
public static void demo(Integer integer,Consumer<Integer> consumer){
consumer.accept(integer);
}
}
Predicate接口,它是断言接口,其中有一个test方法,接收一个任意类型的参数,返回布尔值
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
//Predicate接口演示
public class Test1{
public static void main(String[] args) {
demo(100,(x)->x % 2 ==0 ? true:false);
}
public static boolean demo(Integer integer,Predicate<Integer> predicate){
return predicate.test(integer);
}
}
Funcition接口,函数型接口,其中有一个apply方法,接收T类型对象,返回R类型对象
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
//Function接口演示
public class Test1{
public static void main(String[] args) {
demo(1,(x)->x+"");
}
//接收一个Integer类型的数据,返回一个String类型的数据
public static String demo(Integer i,Function<Integer ,String> function){
String apply = function.apply(i);
return apply;
}
}