java 8 新特性笔记
1. 新特性概述
2. Lambda表达式
2.1 本质
- 函数式接口的实例
2.2 格式
- 举例: (o1,o2) -> Integer.compare(o1,o2);
- 说明:
- -> : lambda操作符 或 箭头操作符
- ->左边:lambda形参列表 (其实就是接口中的抽象方法的形参列表)
- ->右边:lambda体 (其实就是重写的抽象方法的方法体)
2.3 使用
- ->左边:
- 参数类型可以省略,程序会根据接口的泛型而进项类型推断
- 当只有一个参数时,()可以省略
- ->右边:
- 方法体中有多条语句时,格式:{ 语句一;语句二;}
- 当方法体中只有一条语句时,{}可以省略,如果该语句是返回语句,return也可以省略
2.4 示例代码
@Test
public void test1(){
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("我爱北京天安门");
}
};
r1.run();
System.out.println("***********************");
Runnable r2 = () -> System.out.println("我爱北京故宫");
r2.run();
}
@Test
public void test2(){
Comparator<Integer> com1 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1,o2);
}
};
int compare1 = com1.compare(12,21);
System.out.println(compare1);
System.out.println("***********************");
//Lambda表达式的写法
Comparator<Integer> com2 = (o1,o2) -> Integer.compare(o1,o2);
int compare2 = com2.compare(32,21);
System.out.println(compare2);
System.out.println("***********************");
//方法引用
Comparator<Integer> com3 = Integer :: compare;
int compare3 = com3.compare(32,21);
System.out.println(compare3);
}
3. 函数式接口
3.1 定义
- 一个接口中,只声明了一个抽象的方法,则此接口就成为函数式接口
- 可以在一个接口上使用
@FunctionalInterface
注解,可以检查它是否是一个函数式接口(有两个抽象方法就报错) - Lambda表达式的本质:作为函数式接口的实例
3.2 4个基本函数式接口
3.3 基本函数接口的示例
@Test
public void test1(){
happyTime(500, new Consumer<Double>() {
@Override
public void accept(Double aDouble) {
System.out.println("买了瓶矿泉水,价格为:" + aDouble);
}
});
System.out.println("********************");
happyTime(400,money -> System.out.println("价格为:" + money));
}
public void happyTime(double money, Consumer<Double> con){
con.accept(money);
}
@Test
public void test2(){
List<String> list = Arrays.asList("北京","南京","天津","东京","西京","普京");
List<String> filterStrs = filterString(list, new Predicate<String>() {
@Override
public boolean test(String s) {
return s.contains("京");
}
});
System.out.println(filterStrs);
List<String> filterStrs1 = filterString(list,s -> s.contains("京"));
System.out.println(filterStrs1);
}
//根据给定的规则,过滤集合中的字符串。此规则由Predicate的方法决定
public List<String> filterString(List<String> list, Predicate<String> pre){
ArrayList<String> filterList = new ArrayList<>();
for(String s : list){
if(pre.test(s)){
filterList.add(s);
}
}
return filterList;
}
3.4 总结
-
何时使用lambda表达式?
- 当需要对一个函数式接口实例化的时候,可以使用lambda表达式。
-
何时使用java 8 给定的函数式接口?(四个基本函数式接口
Consumer<T>
等)- 如果我们开发中需要定义一个函数式接口,首先看看在已有的jdk提供的函数式接口是否提供了
能满足需求的函数式接口。如果有,则直接调用即可,不需要自己再自定义了。
- 如果我们开发中需要定义一个函数式接口,首先看看在已有的jdk提供的函数式接口是否提供了
4. 方法引用
4.1 定义
- 方法引用可以看做是Lambda表达式深层次的表达
- 方法引用就是Lambda表达式,也就是函数式接口的一个实例,通过方法的名字来指向一个方法
4.2 使用场景
- 想要使用Lambda完成的功能,已经被其他方法实现过了,就可以使用方法引用,避免了方法的冗余
4.3 格式
- 类(或对象) :: 方法名
4.4 使用情况
- 情况1 对象 :: 非静态方法
- 情况2 类 :: 静态方法
- 情况3 类 :: 非静态方法
- 总结
- 情况1和情况2: 接口中的抽象方法的形参列表和返回值类型与方法引用的方法的形参列表和返回值类型相同
- 情况3: 当函数式接口方法的第一个参数是需要引用方法的调用者,并且第二个参数是需要引用方法的参数(或无参数)时:ClassName::methodName
4.5 情况1 代码示例
// 情况一:对象 :: 实例方法
//Supplier中的T get() 形参列表都是空,返回值类型都可以为String
//Employee中的String getName()
@Test
public void test2() {
Employee emp = new Employee(1001,"Tom",23,5600);
Supplier<String> sup1 = () -> emp.getName();
System.out.println(sup1.get()); //方法调用
System.out.println("*******************");
Supplier<String> sup2 = emp::getName;
System.out.println(sup2.get());
}
//Consumer中的void accept(T t)
//PrintStream中的void println(T t)
@Test
public void test1() {
Consumer<String> con1 = str -> System.out.println(str);
con1.accept("北京");
System.out.println("*******************");
PrintStream ps = System.out;
Consumer<String> con2 = ps::println;
con2.accept("beijing");//方法调用时会传入参数,因此ps::println;没有写参数
}
4.6 情况2 代码示例
// 情况二:类 :: 静态方法
//Function中的R apply(T t)
//Math中的Long round(Double d)
@Test
public void test4() {
Function<Double,Long> func = new Function<Double, Long>() {
@Override
public Long apply(Double d) {
return Math.round(d);
}
};
System.out.println("*******************");
Function<Double,Long> func1 = d -> Math.round(d);
System.out.println(func1.apply(12.3));
System.out.println("*******************");
Function<Double,Long> func2 = Math::round;
System.out.println(func2.apply(12.6));
}
//Comparator中的int compare(T t1,T t2)
//Integer中的int compare(T t1,T t2)
@Test
public void test3() {
Comparator<Integer> com1 = (t1,t2) -> Integer.compare(t1,t2);
System.out.println(com1.compare(12,21));
System.out.println("*******************");
Comparator<Integer> com2 = Integer::compare;
System.out.println(com2.compare(12,3));
}
4.7 情况3 代码示例
// 情况:类 :: 实例方法 (难度)
//BiPredicate中的boolean test(T t1, T t2);
//String中的boolean t1.equals(t2)
@Test
public void test6() {
BiPredicate<String,String> pre1 = (s1,s2) -> s1.equals(s2);
System.out.println(pre1.test("abc","abc"));
System.out.println("*******************");
BiPredicate<String,String> pre2 = String :: equals;
System.out.println(pre2.test("abc","abd"));
}
// Comparator中的int comapre(T t1,T t2)
// String中的int t1.compareTo(t2)
@Test
public void test5() {
Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);
System.out.println(com1.compare("abc","abd"));
System.out.println("*******************");
Comparator<String> com2 = String :: compareTo;
System.out.println(com2.compare("abd","abm"));
}
// Function中的R apply(T t)
// Employee中的String getName();
@Test
public void test7() {
Employee employee = new Employee(1001, "Jerry", 23, 6000);
Function<Employee,String> func1 = e -> e.getName();
System.out.println(func1.apply(employee));
System.out.println("*******************");
Function<Employee,String> func2 = Employee::getName;
System.out.println(func2.apply(employee));
}
5. 构造器引用
5.1 格式
- 类名::new
5.2 使用说明
- 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。抽象方法的返回值类型即为构造器所属的类的类型
5.3 示例
//Supplier中的T get()
//Employee的空参构造器:Employee()
@Test
public void test1(){
Supplier<Employee> sup = new Supplier<Employee>() {
@Override
public Employee get() {
return new Employee();
}
};
System.out.println("*******************");
Supplier<Employee> sup1 = () -> new Employee();
System.out.println(sup1.get());
System.out.println("*******************");
Supplier<Employee> sup2 = Employee :: new;
System.out.println(sup2.get());
}
//Function中的R apply(T t)
@Test
public void test2(){
Function<Integer,Employee> func1 = id -> new Employee(id);
Employee employee = func1.apply(1001);
System.out.println(employee);
System.out.println("*******************");
Function<Integer,Employee> func2 = Employee :: new;
Employee employee1 = func2.apply(1002);
System.out.println(employee1);
}
//BiFunction中的R apply(T t,U u)
@Test
public void test3(){
BiFunction<Integer,String,Employee> func1 = (id,name) -> new Employee(id,name);
System.out.println(func1.apply(1001,"Tom"));
System.out.println("*******************");
BiFunction<Integer,String,Employee> func2 = Employee :: new;
System.out.println(func2.apply(1002,"Tom"));
}
6. 数组引用
6.1 格式
- 数组类型[] :: new
6.2 示例
//Function中的R apply(T t)
@Test
public void test4(){
Function<Integer,String[]> func1 = length -> new String[length];
String[] arr1 = func1.apply(5);
System.out.println(Arrays.toString(arr1));
System.out.println("*******************");
Function<Integer,String[]> func2 = String[] :: new;
String[] arr2 = func2.apply(10);
System.out.println(Arrays.toString(arr2));
}
7. Stream API
7.1 定义
- 是 java8提供的一套api,使用这套api可以对内存中的数据进行过滤、排序、映射、归约等操作。类似于sql对数据库中表的相关操作
- Stream关注的是对数据的运算,与CPU打交道
- 集合关注的是数据的存储,与内存打交道
7.2 特点
- Stream 自己不会存储元素。
- Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
- Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。
7.3 使用流程
1️⃣ Stream的实例化
2️⃣ 一系列的中间操作(过滤、映射、…)
3️⃣ 终止操作
说明:
- 一个中间操作链,对数据源的数据进行处理
- 只有执行终止操作,才会执行操作链,并产生结果,之后,不会再被使用
7.4 创建Stream流
- 通过集合
Collection
default Stream<E> stream()
: 返回一个顺序流, eg:listObj.stream()
default Stream<E> parallelStream()
: 返回一个并行流 eg:listObj.parallelStream()
- 通过数组
- 调用
Arrays
类的static <T> Stream<T> stream(T[] array)
: 返回一个流 eg:Arrays.stream(arrObj)
- 调用
- 通过Stream的of()
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
- 创建无限流
- 迭代,
public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
- 生成,
public static<T> Stream<T> generate(Supplier<T> s)
}
- 迭代,
通过集合创建 Stream示例
@Test
public void test1(){
List<Employee> employees = EmployeeData.getEmployees();
// default Stream<E> stream() : 返回一个顺序流
Stream<Employee> stream = employees.stream();
// default Stream<E> parallelStream() : 返回一个并行流
Stream<Employee> parallelStream = employees.parallelStream();
}
通过数组创建 Stream示例
@Test
public void test2(){
int[] arr = new int[]{1,2,3,4,5,6};
//调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流
IntStream stream = Arrays.stream(arr);
Employee e1 = new Employee(1001,"Tom");
Employee e2 = new Employee(1002,"Jerry");
Employee[] arr1 = new Employee[]{e1,e2};
Stream<Employee> stream1 = Arrays.stream(arr1);
}
通过Stream的of()创建 Stream示例
@Test
public void test3(){
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
}
通过无限流创建 Stream示例
@Test
public void test4(){
// 迭代
// public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
//遍历前10个偶数
Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);
// 生成
// public static<T> Stream<T> generate(Supplier<T> s)
Stream.generate(Math::random).limit(10).forEach(System.out::println);
}
7.5 中间操作API
7.6 终止操作的API
Collector需要使用Collectors提供实例。
8. Optional类
8.1 定义
- 为了解决java中的空指针问题而生
Optional<T>
类(java.util.Optional) 是一个容器类,它可以保存类型T的值,代表这个值存在。或者仅仅保存null
,表示这个值不存在。原来用 null 表示一个值不存在,现在 Optional 可以更好的表达这个概念。并且可以避
免空指针异常。