函数式接口
- 函数式接口只能有一个抽象方法,
- 函数式接口可以有默认的方法default方法和static方法,但抽象方法只能有一个
- 函数式接口可以用**@FunctionalInterface**注解进行标注
- 可以重写Object内置的方法,比如equals,hashcode等等
lambda表达式
跟js的箭头函数很像。在函数式接口的简化过程中**(参数)->{…方法体}**
匿名内部类的简写方式
方法引入
- 静态方法引入: 类名::方法名
- 对象方法引入: 类名 :: 实例方法
- 实例方法引入: new 对象 对象实例::方法引入
- 构造函数引入: 类名::new
注意点:方法引入参数和返回类型必须和函数接口的参数列表和返回类型必须保持一致。
示例
public static void staticMethod(Integer a){
System.out.println("我是静态方法:"+a);
}
public String getString(String s){
return "hello world"+s;
}
@Test
public void test5(){
//静态方法引入
((MessageInterface) TestStream::staticMethod).get(5);
//实例方法引入
StringInterface stringInterface = new TestStream() :: getString;
System.out.println(stringInterface.get("你好"));
//构造函数引入
ObjInterface objInterface = User :: new;
System.out.println(objInterface.get("张三",19));
}
}
@FunctionalInterface
interface ObjInterface{
User get(String username,int age);
}
@FunctionalInterface
interface StringInterface{
String get(String str);
}
@FunctionalInterface
interface MessageInterface{
void get(int a);
}
stream流
使用stream的步骤如下:
6. 创建stream;
7. 通过一个