Java8—Lambda、stream API
一、Lambda表达式
前提准备
Employee类为接下来测试Lambda表达式和stream API提供数据支持。
public class Employee {
private long eid;//员工ID
private String name;//员工姓名
private String department;//员工住址
private double salary;//员工薪水
private int age;//员工年龄
public static List<Employee> getEmployeesList(){
Employee e1 = new Employee(1001, "老大", "1-101", 4500, 23);
Employee e2 = new Employee(1002, "老二", "1-102", 5000, 24);
Employee e3 = new Employee(1003, "老三", "1-103", 5500, 25);
Employee e4 = new Employee(1004, "老四", "1-104", 6000, 26);
Employee e5 = new Employee(1005, "老五", "1-105", 6500, 27);
ArrayList<Employee> employeesList = new ArrayList<>();
employeesList.add(e1);
employeesList.add(e2);
employeesList.add(e3);
employeesList.add(e4);
employeesList.add(e5);
return employeesList;
}
}
1. 语法
(1) -> (2)
左侧1是输入的参数列表,右侧2是需要执行的操作,又叫Lambda体。
Lambda表达式其实是在实现函数式接口中的抽象方法,是接口的一个实现类的对象,(1)对应抽象方法的参数列表,(2)对应方法实现时的具体操作。
1.1 无参数 无返回值
// () -> System.out.println(x)
Runnable runnable = () -> System.out.println("无参数无返回值");
runnable.run();
1.2 一个参数 无返回值
// (x)-> System.out.println(x), 此时(x)的()可以省略
Consumer<Integer> consumer = (x) -> System.out.println(x);
consumer.accept(1);
1.3 多个参数 多条语句 有返回值
Comparator<Integer> com = (x, y) -> {
System.out.println("两个参数多条语句有返回值");
return Integer.compare(x, y);
};
//只有一条语句时,{}和return可以省略
//Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
2. 函数式接口
2.1 函数式接口
接口中只有一个抽象方法的接口,用注解@FunctionalInterface
修饰。
2.2 内置的四大函数式接口
Consumer<T>: 消费型接口
void accept(T t);
Supplier<T>: 供给型接口
T get();
Functional<T, R>: 函数型接口
R apply(T t);
Predicate<T>: 断言型接口
boolean test(T t);
2.2.1 Consumer
//Consumer<T> void accept(T t);
@Test
public void test1() {
testConsumer(400, (c)-> System.out.println("消费 " + c + " 元"));
//消费 400 元
}
public void testConsumer(int money, Consumer<Integer> consumer){
consumer.accept(money);
}
2.2.2 Supplier
//Supplier<T> T get();
@Test
public void test2() {
List<Integer> list = testSupplier(5, () -> (int) (Math.random()*10));
list.forEach(System.out::print);
//84879
}
//返回num个随机整数
public List<Integer> testSupplier(int num, Supplier<Integer> supplier){
ArrayList<Integer> list = new ArrayList<>();
for(int i=0; i<num; i++){
Integer integer = supplier.get();
list.add(integer);
}
return list;
}