JAVA8 新特性学习笔记
Lambda 表达式
Lambda允许把函数作为一个方法的参数(函数作为参数传递进方法中)或者把代码看成数据。
一个lambda可以由逗号分隔的参数列表、-> 符号与函数体三部分表示。
Lambda可以引用类的成员变量与局部变量(如果这些变量不是final的话,它们会被隐含的转维final,这样效率更高,如下文中的tag。
List<String> array = new ArrayList<String>();
String tag = "";
//......数组赋值......
array.forEach(it -> System.out.println(it + tag));
Lambda可能会返回一个值,返回值的类型也是有编译器推测出来的。如果Lambda的函数体只有一行的话,那么没有必要显式使用return语句。
Arrays.asList("a", "b", "c").sort((e1, e2) -> e1.compareTo(e2));
// 等价于下
Arrays.asList("a", "b", "c").sort((e1, e2) -> {
int result = e1.compareTo(e2);
return result;
});
Functional接口以及@FunctionalInterface注解
函数式接口就是一个具有一个方法的普通接口。像这样的接口,可以被隐式转换为Lambda表达式。
为了解决函数式接口的脆弱性,Java8增加了一种特殊的注解@FunctionalInterface(Java8中所有类库的已有接口都添加了@FunctionalInterface注解)
@FunctionalInterface
interface Functional {
void method();
}
ps:默认方法和静态方法并不影响函数式接口的契约
方法引用
方法引用提供了非常有用的语法,可以直接引用已有Java类或对象(实例)的方法或构造器。与lambda联合使用,方法引用可以使语言的构造更紧凑简洁,减少冗余代码。
以List的sort方法为例,sort方法接收一个Comparator函数式接口,接口中唯一的抽象方法compare接收两个参数返回一个int类型值,下方是Comparator接口定义
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
创建Student类用于演示 静态方法compareStudentByScore结构保持与Comparator函数接口的compare()方法声明一致;
public class Student {
private String name;
private int score;
public static int compareStudentByScore(Student student1,Student student2){
return student1.getScore() - student2.getScore();
}
**getter setter 构造省略***
}
1. 类名::静态方法名
List<Student> studens = new ArrayList<Student>();
-----给studens数组添加数据------
// Student - 类名
// compareStudentByScore - Student 中静态方法名
students.sort(Student::compareStudentByScore);
2. 对象::实例方法名
需要自定义一个用于比较Student元素的类StudentComparator
public class StudentComparator {
public int compareStudentByScore(Student student1,Student student2){
return student2.getScore() - student1.getScore();
}
}
StudentComparator中定义了一个非静态的,实例方法 compareStudentByScore,同样该方法的定义满足Comparator接口的compare方法定义,所以这里可以直接使用 对象::实例方法名 的方式使用方法引用来替换lambda表达式
List<Student> studens = new ArrayList<Student>();
-----给studens数组添加数据------
StudentComparator studentComparator = new StudentComparator();
// studentComparator - StudentComparator 的实例
// compareStudentByScore - StudentComparator 的实例方法名
students.sort(studentComparator::compareStudentByScore);
3. 类名::实例方法名
改造Student的compareStudentByScore方法如下(去掉static关键字,参数只有一个)
public int compareStudentByScore(Student student){
return this.getScore() - student.getScore();
}
接收一个Student对象和当前调用该方法的Student对象的分数进行比较即可。现在我们就可以使用 类名::实例方法名 这种方式的方法引用替换lambda表达式了
students.sort(Student::compareStudentByScore);
4. 类名::new
Student类构造方法引用创建了supplier实例,以后通过supplier.get()就可以获取一个Student类型的对象,前提是Student类中存在无参构造方法。
Supplier<Student> supplier = Student::new;
默认方法
默认方法就是一个在接口里面有了一个实现的方法。
新工具
新的编译工具,如:Nashorn引擎 jjs、 类依赖分析器jdeps。
Stream API
新添加的Stream API(java.util.stream) 把真正的函数式编程风格引入到Java中。
Date Time API
加强对日期与时间的处理。
Optional 类
Optional 类已经成为 Java 8 类库的一部分,用来解决空指针异常。
Nashorn, JavaScript 引擎
Java 8提供了一个新的Nashorn javascript引擎,它允许我们在JVM上运行特定的javascript应用。