lambda表达式必须是函数式接口;lambda表达式表示函数接口的实例。
函数式接口
函数式接口用@FunctionalInterface来标记检验,
接口里必须有且只有一个抽象方法,但可以有多个由default修饰的默认方法和静态方法;
@FunctionalInterface
public interface IBooleanSuppiler {
abstract boolean getAsBoolean();
default String getById() {
return null;
}
static String getName() {
return null;
}
}
普通方式实现该接口,就是写一个子类继承这个接口,然后在子类里重写该方法,
若要调用该接口里的方法则通过new子类,然后调用接口里的方法。
匿名内部类实现该接口
通过匿名内部类在方法体里重写该接口里的方法,进行实现。
如:
new BooleanSupplier(){ //匿名内部类
@Override
public boolean getAsBoolean() {
return false;
}
};
lambda表达式就是对匿名内部类的一个优化。
new BooleanSupplier(){ //匿名内部类
@Override
public boolean getAsBoolean() {
return false;
}
};
省略接口名和方法名
==> () - > {return false}
省略大括号和return
==> () - > false
Collections.addAll(list,1,2,3,4,5,6);
将元素批量添加进list
集合中
实现comparator接口方式
list.sort(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge()-o2.getAge();
}
});
System.out.println(list);
Lambada表达式方式
list.sort((o1,o2) -> o1.getAge()- o2.getAge());
迭代器循环遍历删除满足条件的元素
Iterator<Person> it = list.iterator();
while (it.hasNext()){
if(it.next().getAge()>13){
it.remove();
}
}
System.out.print(list+" ");
Lambada表达式方式
list.removeIf(ele-> ele.getAge()>12);
System.out.println(list);
在Lambada表达式中引用的一定是
常量
,就算不是,系统也会自动添加final修饰
//把代码逻辑当做参数进行传递
int age = getAge(a -> Integer.parseInt(a), "12");
System.out.println(age);
}
public static int getAge(Function<String,Integer> function, String args){
return function.apply(args);
}
Shift + F6
批量修改变量名
方法引用共分为四类:
1.类名::静态方法名
2.对象::实例方法名
3.类名::实例方法名
4.类名::new
CompareTo()是非静态方法
只能用对象调用。
compare()是静态的
可以用类名调用。
Collections.sort(emp,(o1,o2)->{
if(o1.getAge()==o2.getAge()){
return o1.getName().compareTo(o2.getName());
}else{
return Integer.compare(o1.getAge(),o2.getAge());
}
});
compareTo内部其实也是直接调用的compare方法
.
对象大于目标参数,返回1
对象小于目标参数,返回-1
对象等于目标参数,返回0
Stream
- 通过collection系列集合提供的 stream()方法创建
List<String> list =new ArrayList<>();
Stream<String> stream = list.stream();
- 通过Arrays中的静态方法stream()获取数组流
Employee[] emps = new Employee[10];
stream<Employee> stream = Arrays.stream(emps);
- 通过stream类中的静态方法of()
Stream<String> stream = Stream.of("a","b","c");
- 创建无限流,
Stream<Integer> stresam = Stream.iterate(0,(x)->x+2;
stream.limit(10).forEach(System.out::println);
Stream的中间操作