JDK8新特性
JDK8新特性
1、FunctionInterface 是什么?和Lambda表达式有什么关系?
package com.wood.functional;
/**
* @Description: 函数式接口
* @Author wood
* @Date 2019-08-15
*
* @FunctionalInterface 声明一个接口是函数式接口,目的是可以用lambda表达式的方式实现接口
* 函数式接口只能包含一个抽象方法,重写父类的方法不算
* Java中所有的对象都是继承自Object,所以MyInterface实际上是继承自Object,所以有toString()
*
* 在将函数作为一等公民的语言(JavaScript、Python)中,Lambda表达式(匿名函数、闭包)是函数,
* 但在Java中,Lambda表达式是对象(Java中一切皆对象),必须依附于一类特别的对象FunctionalInterface
*
* JDK8强调传递行为,而不仅仅是数据
*
*/
@FunctionalInterface
public interface MyInterface {
// 函数式接口只能包含一个抽象方法
void test();
// 重写父类(Object)的方法不算,所以能够编译通过
String toString();
}
package com.wood.functional;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @Description: 测试函数式接口
* @Author wood
* @Date 2019-08-15
*/
public class MyTest {
public void testInterface(MyInterface myInterface) {
myInterface.test();
}
public static void main(String[] args) {
MyTest myTest = new MyTest();
myTest.testInterface(new MyInterface() {
@Override
public void test() {
System.out.println("调用函数式接口test():通过new MyInterface()的方式");
}
});
myTest.testInterface(() -> System.out.println("调用函数式接口test():通过lambda表达式的方式"));
MyInterface myInterface = () -> {
System.out.println("这是MyInterface的实现,是一个匿名函数");
};
myTest.testInterface(myInterface);
}
}
2、FunctionInterface函数式接口强调传递的是行为,不是数据。
package com.wood.functional;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @Description: 测试函数式接口
* @Author wood
* @Date 2019-08-15
*/
public class MyTest {
public void testInterface(MyInterface myInterface) {
myInterface.test();
}
public static void main(String[] args) {
MyTest myTest = new MyTest();
myTest.testInterface(new MyInterface() {
@Override
public void test() {
System.out.println("调用函数式接口test():通过new MyInterface()的方式");
}
});
myTest.testInterface(() -> System.out.println("调用函数式接口test():通过lambda表达式的方式"));
MyInterface myInterface = () -> {
System.out.println("这是MyInterface的实现,是一个匿名函数");
};
myTest.testInterface(myInterface);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
/**
* JDK8开始,接口可以有默认实现,用default关键字修饰
* default void forEach(Consumer<? super T> action) {
* Objects.requireNonNull(action);
* for (T t : this) {
* action.accept(t);
* }
* }
* */
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
System.out.println(integer);
}
});
// 方法引用
list.forEach(System.out::println);
/**
* JDK8强调传递行为,而不仅仅是数据
* */
System.out.println("-----JDK8强调传递行为,而不仅仅是数据-----");
System.out.println(myTest.calculate(2, t -> 2 * t));
System.out.println(myTest.calculate(2, t -> t * t));
System.out.println(myTest.calculate(2, t -> t + 1));
System.out.println("-----compose-----(先执行t -> t + 1 再执行t -> 2 * t)");
System.out.println(myTest.compose(2, t -> 2 * t, t -> t + 1)); // 6
System.out.println("-----andThen-----(先执行t -> 2 * t 再执行t -> t + 1)");
System.out.println(myTest.andThen(2, t -> 2 * t, t -> t + 1)); // 5
System.out.println("-----BiFunction是Function的增强形式-----");
/**
* 如果是JDK7传统的做法是,需要写4个方法(加、减、乘、除)
* 而JDK8可以借助于BiFunction来完成,传递的是行为
* */
System.out.println(myTest.biFunction(1, 2, (t1, t2) -> t1 + t2));
System.out.println(myTest.biFunction(1, 2, (t1, t2) -> t1 - t2));
System.out.println(myTest.biFunction(1, 2, (t1, t2) -> t1 * t2));
System.out.println(myTest.biFunction(1, 2, (t1, t2) -> t1 / t2));
System.out.println("-----biFunction andThen-----(先执行(t1, t2) -> t1 + t2 再执行t -> t * t)");
System.out.println(myTest.biFunctionAndThen(1, 2, (t1, t2) -> t1 + t2, t -> t * t)); // 9
// stream获取流并对流操作,操作完成后再将它转换为集合
System.out.println(list.stream().filter(t -> t > 2).collect(Collectors.toList()));
// 原来的集合不变,流操作返回的是新集合
System.out.println(list);
System.out.println(myTest.biFunctionFilter(3, list, (value, integerList) -> integerList.stream().filter(t -> t > value).collect(Collectors.toList())));
}
/**
* 计算
* 高阶函数:如何一个方法接收一个函数作为参数或返回值是一个函数
* @param t 输入值
* @param function 对t执行的行为函数,Function<Integer(输入类型), Integer(输出类型)>
* @return 操作后的值
*/
public int calculate(int t, Function<Integer, Integer> function) {
return function.apply(t);
}
public int compose(int t, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
// 先执行function2的行为,再执行function1的行为
return function1.compose(function2).apply(t);
}
public int andThen(int t, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
// function1 -> function2
return function1.andThen(function2).apply(t);
}
public int biFunction(int t1, int t2, BiFunction<Integer, Integer, Integer> biFunction) {
// BiFunction<A, B, Integer> biFunction 对入参A、B执行biFunction行为返回Integer类型的值
// Function是一个输入,BiFunction是两个输入
return biFunction.apply(t1, t2);
}
public int biFunctionAndThen(int t1, int t2, BiFunction<Integer, Integer, Integer> biFunction, Function<Integer, Integer> function) {
// andThen表示先执行biFunction,再执行function
return biFunction.andThen(function).apply(t1, t2);
}
public List<Integer> biFunctionFilter(int t, List<Integer> list, BiFunction<Integer, List<Integer>, List<Integer>> biFunction) {
return biFunction.apply(t, list);
}
}
3、Predicate是什么?如何应用?
public List<Integer> conditionFilter(List<Integer> list, Predicate<Integer> predicate) {
return list.stream().filter(predicate).collect(Collectors.toList());
}
public List<Integer> conditionAndFilter(List<Integer> list, Predicate<Integer> predicate1, Predicate<Integer> predicate2) {
return list.stream().filter(predicate1.and(predicate2)).collect(Collectors.toList());
}
// Predicate表示断言条件,给定输入判断是否符合条件
System.out.println("-----Predicate断言条件-----");
Predicate<Integer> predicate = t -> t > 2;
System.out.println(predicate.test(3));
System.out.println("-----给定输入和条件,输出想要的数据-----");
System.out.println(myTest.conditionFilter(list, t -> t > 2));
System.out.println(myTest.conditionFilter(list, t -> t % 2 == 0));
System.out.println(myTest.conditionFilter(list, t -> t % 2 == 1));
System.out.println(myTest.conditionFilter(list, t -> true));
System.out.println(myTest.conditionFilter(list, t -> false));
System.out.println("多个Predicate执行and操作,也就是多个条件 && ==> t > 2 && t % 2 == 0");
System.out.println(myTest.conditionAndFilter(list, t -> t > 2, t -> t % 2 == 0));
4、Supplier是什么?
/**
* Supplier 不接收参数,返回一个对象
* Gets a result
* T get ();
* */
Supplier<Student> supplier = () -> new Student("小伍", 20);
System.out.println(supplier.get().toString());
5、可选类型Optional
package com.wood.functional;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
* @Description: 可选类型Optional
* @Author wood
* @Date 2019-08-18
*/
public class OptionalTest {
/**
* 可选类型Optional被设计用来防止空指针异常NullPointerException
* */
public static void main(String[] args) {
Optional<String> optional = Optional.of("hello");
// 如果对象存在就打印
if (optional.isPresent()) {
System.out.println(optional.get());
}
// 推荐的optional的使用方式
optional.ifPresent(System.out::println);
optional = Optional.empty();
System.out.println(optional.orElse("如果optional是空则输出这句话"));
System.out.println(optional.orElseGet(() -> "如果optional是空,则通过Supplier获取值"));
/**
* Optional具体应用
* */
Student student1 = new Student("小伍", 18);
Student student2 = new Student("马拉松", 100);
List<Student> list = Arrays.asList(student1, student2);
Optional<Student> optionalStudent = Optional.ofNullable(student2);
System.out.println(optionalStudent.map(student -> student.getAge() > 50 ? student : null).orElse(student1));
}
}
6、方法引用(函数指针)
package com.wood.functional;
/**
* @Description: 学生
* @Author wood
* @Date 2019-08-18
*/
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
/**
* 静态方法,可以用来做方法应用 Student::desc
* @param student
*/
public static void desc(Student student) {
String desc = "学生{" +
"姓名='" + student.getName() + '\'' +
", 年龄=" + student.getAge() +
'}';
System.out.println(desc);
}
}
/**
* Optional具体应用
* */
Student student1 = new Student("小伍", 18);
Student student2 = new Student("马拉松", 100);
List<Student> list = Arrays.asList(student1, student2);
Optional<Student> optionalStudent = Optional.ofNullable(student2);
System.out.println(optionalStudent.map(student -> student.getAge() > 50 ? student : null).orElse(student1));
/**
* 方法引用(函数指针)
* public static void desc(Student student) { ... }
* 类名::静态方法
* */
list.forEach(student -> Student.desc(student));
list.forEach(Student::desc);