文章目录
JDK8新特性
1. 函数式接口
概念: 只有一个抽象方法的接口称之为函数式接口。函数式接口可以使用注解@FunctionalInterface
进行修饰
2. Lambda表达式
概念及语法格式
λ表达式可以理解为将代码或者方法作为参数进行传递去执行。
λ表达式可以拆分为两部分
左侧:参数列表
右侧:所需要执行的功能,及λ体
语法格式1:无参数,无返回值
@Test
public void test(){
// () -> System.out.println("Hello");
Runnable a = new Runnable(){
@Override
public void run(){
System.out.println("Hello")
}
};
//等同于
Runnable a1 = () -> System.out.println("Hello");
a1.run();
}
语法格式2:有一个参数,无返回值(若只有一个参数 小括号可以省略不写)
@Test
public void test(){
//Consumer被注解@FunctionalInterface修饰的接口(函数式接口) 唯一抽象方法 void accept(T t);
//左侧参数 -> 右侧执行体
Consumer<String> con = (x) -> System.out.println(x);
// x -> System.out.println(x);
con.accept("hahah");
}
语法格式3:有两个以上的参数,并且lambda体中有多条语句 (若lambda体中只有一条语句,return 和 大括号都可以省略不写)
@Test
public void test(){
//Comparator被注解@FunctionalInterface的接口 举例抽象方法 int compare(T o1,T o2);
Comparator<Integer> com = (x,y) -> {
System.out.println("hhaha0");
return (x < y) ? -1 : ((x == y) ? 0 : 1);
};
com.compare(1,2);
}
注意:lambda表达式的参数类型可以省略不写,因为jvm编译器可以从上下文推断出数据类型。即“类型推断”如果要在参数里面写数据类型,都要写上。
实例1
class Employee {
private String name;
private int age;
private double salary;
//省略 get and set and constructor
}
interface MyPredicate<T> {
boolean test(T t);
}
public class Test{
static List<Employee> list = Arrays.asList(
new Employee("张三",10,1),
new Employee("里斯",20,1),
new Employee("王五",16,1),
new Employee("二三",30,1)
);
public static List<Employee> filterEmployee(List<Employee> list,MyPredicate<Employee> mp){
List<Employee> emps = new ArrayList<>();
for (Employee employee : list) {
if(mp.test(employee)){
emps.add(employee);
}
}
return emps;
}
@org.junit.Test
public void test1(){
//需要使用自定义的方法,过滤年龄等于等于15岁的员工
List<Employee> list2 = filterEmployee(list,(e) -> e.getAge() >= 15);
list2.stream().map(Employee::getName).forEach(System.out::println);
}
@org.junit.Test
public void test2(){
//可以使用stream进行list集合的过滤 不使用自定义接口
List<Employee> list2 = list.stream().filter((e) -> e.getAge() >= 15).collect(Collectors.toList());
list2.stream().map(Employee::getName).forEach(System.out::println);
}
}
实例2
创建一个MyFun接口使用@FunctionalInterface注解,并创建一个抽象方法Integer getValue(Integer num);在Test类对变量进行某种操作。
@FunctionalInterface
interface MyFun{
Integer getValue(Integer num);
}
public class Test{
@org.junit.Test
public void Test(){
operation(100,num -> ++num);
}
/**
* param1 num : 传入的整形数
* param2 mf : 实现某种方式对 整形数 进行操作。
**/
public Integer operation(Integer num,MyFun mf){
return mf.getValue(num);
}
}
四大核心函数式接口
Consumer : 消费性接口 void accept(T t);
Supplier : 供给性接口 T get();
Function<T,R> : 函数性接口 T代表参数,R代表返回值 R apply(T t);
Predicate :断言性接口 boolean test(T t);
// 举例:消费型接口Consumer<T>的使用
class Test{
@org.junit.Test
publilc void test(){
happy(10000,(money)->System.out.println("happy消费"+money+"元"));
}
public void happy(double money,Consumer<double> con){
con.accept(money);
}
}
lambda方法引用
主要有三种语法格式:
对象::实例方法名
类::静态方法名
类::实例方法名
class Test{
//对象::实例方法名
@org.junit.Test
public void test(){
Consumer<String> con = (x) -> System.out.println(x);
con.accept("haha");