两个用于测试的类
员工:
public class Employee {
private int id;
private String name;
private int age;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public Employee() {
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public Employee(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
if (id != employee.id) return false;
if (age != employee.age) return false;
if (Double.compare(employee.salary, salary) != 0) return false;
return name != null ? name.equals(employee.name) : employee.name == null;
}
@Override
public int hashCode() {
int result;
long temp;
result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + age;
temp = Double.doubleToLongBits(salary);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
/**
* 提供用于测试的数据
*
*/
public class EmployeeData {
public static List<Employee> getEmployees(){
List<Employee> list = new ArrayList<>();
list.add(new Employee(1001, "马化腾", 34, 6000.38));
list.add(new Employee(1002, "马云马", 12, 9876.12));
list.add(new Employee(1003, "刘强东", 33, 3000.82));
list.add(new Employee(1004, "雷军", 26, 7657.37));
list.add(new Employee(1005, "李彦宏", 65, 5555.32));
list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
list.add(new Employee(1007, "任正非", 26, 4333.32));
list.add(new Employee(1008, "尔扎克伯格", 35, 2500.32));
return list;
}
}
一、Lambda表达式的基本语法。
1.格式: lambda形参列表 -> lambda体
2.说明: -> : lambda操作符 或箭头操作符
->左边 :lambda表达式的形参列表
->右边:lambda表达式的执行语句,称为lambda体
3.如何使用:分为六种情况
public class LambdaTest {
//情况六:lambda体如果只有一条执行语句,可以省略这一对{}.
//特别的,如果此唯一的一条执行语句是return,则除了省略一对{}之外,return关键字也可以省略
@Test
public void test7(){
Comparator<Integer> com1 = (o1,o2) -> o1.compareTo(o2);
int value = com1.compare(12, 34);
System.out.println(value);
}
//情况五:lambda表达式的形参列表有两个或两个以上的变量,lambda体有多条执行语句,甚至有返回值
@Test
public void test6(){
Comparator<Integer> com1 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
System.out.println(o1);
System.out.println(o2);
// return Integer.compare(o1,o2);
return o1.compareTo(o2);
}
};
int value = com1.compare(12, 34);
System.out.println(value);
System.out.println("******************");
Comparator<Integer> com2 = (o1,o2) -> {
System.out.println(o1);
System.out.println(o2);
// return Integer.compare(o1,o2);
return o1.compareTo(o2);
};
int value1 = com2.compare(32, 12);
System.out.println(value1);
}
//情况四:针对于情况三进行迭代。
//如果lambda表达式的形参列表只有一个变量,则可以省略一对()
@Test
public void test5(){
Consumer<String> con1 = s -> {
System.out.println(s);
};
con1.accept("你好我也好!");
}
//以前在java程序中出现的类型推断
@Test
public void test4(){
//举例1:
int[] arr = new int[]{1,2,3,4};
//类型推断
int[] arr1 = {1,2,3,4};
int[] arr2 ;
arr2 = new int[]{1,2,3,4};
//举例2:
List<String> list = new ArrayList<String>();
//类型推断
List<String> list1 = new ArrayList<>();
//举例3
method(new HashMap<>());
}
public void method(HashMap<String,Employee> map){
}
//情况三:针对于情况二进行迭代。lambda形参列表的变量的数据类型可以省略
//说明:java编译器可以根据上下文推断出变量的数据类型,故可以省略:类型推断
@Test
public void test3(){
Consumer<String> con1 = (s) -> {
System.out.println(s);
};
con1.accept("你好我也好!");
}
//情况二:lambda形参列表有一个参数,无返回值
@Test
public void test2(){
Consumer<String> con = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
con.accept("昨天过的挺好!");
System.out.println("*************");
Consumer<String> con1 = (String s) -> {
System.out.println(s);
};
con1.accept("你好我也好!");
}
//情况一:无形参,无返回值
@Test
public void test1(){
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("昨天是七夕情人节!");
}
};
Thread t1 = new Thread(r);
t1.start();
System.out.println("*************");
Runnable r1 = () -> {
System.out.println("你们有没有因为爱情而鼓掌呢?");
};
Thread t2 = new Thread(r1);
t2.start();
}
}
总结:
1)lambda形参列表:如果有形参的话,都可以省略变量的数据类型 ---类型推断
如果形参列表只有一个形参,还可以省略一对()
2)lambda体:正常情况下,需要使用一对{}包起来所有的执行语句。
特别的,①lambda体如果只有一条执行语句,可以省略这一对{}.
②如果此唯一的一条执行语句是return,则除了省略一对{}之外,return关键字也可以省略
二、什么是函数式接口
1.特点:如果一个接口中只有唯一的一个抽象方法,则此接口称为函数式接口
2.可以在接口的声明上使用@FunctionalInterface注解去校验一个接口是否是函数式接口
3.lambda表达式的使用依赖于函数式接口
4.lambda表达式即为函数式接口的实例。
@FunctionalInterface
public interface MyFunction {
public String getValue(String str);
}
只要一个对象是函数式接口的实例,那么该对象就可以用Lambda表达式来表示。
所以以前用匿名类表示的现在都可以用Lambda表达式来写。
java8中关于Lambda表达式提供的4个基本的函数式接口
1.Consumer<T> :消费型接口
void accept(T t) 输入一个值没有返回值
2.Supplier<T> : 供给型接口
T get() 没有输入值,返回一个值
3. Function<T,R> : 函数型接口
R apply(T t) 有输入值,有返回值
4. Predicate<T> : 断定型接口
boolean test(T t) 有输入值,只能返回boolean
public class LambdaTest1 {
//4. Predicate<T> : 断定型接口
//boolean test(T t)
@Test
public void test4(){
List<String> list = Arrays.asList("北京","南京","东京","西京","普京","上海","深圳");
List<String> data = getStrings(list, s -> s.contains("京"));
System.out.println(data);
}
public List<String> getStrings(List<String> list, Predicate<String> pre){
List<String> data = new ArrayList<>();
for (String s : list) {
if(pre.test(s)){
data.add(s);
}
}
return data;
}
//3. Function<T,R> : 函数型接口
//R apply(T t)
@Test
public void test3(){
strHandler(" hel lo ",str -> str.trim());
strHandler("世界那么大,我想去看看",str -> str.substring(2,5));
}
public void strHandler(String str, Function<String,String> func){
String s = func.apply(str);
System.out.println(s);
}
// 2.Supplier<T> : 供给型接口
// T get()
@Test
public void test2(){
List<Double> list = getRandomValue(10, () -> Math.random() * 100);
for (Double d : list) {
System.out.println(d);
}
}
public List<Double> getRandomValue(int num, Supplier<Double> sup){
List<Double> list = new ArrayList<>();
for(int i = 0;i < num;i++){
list.add(sup.get());
}
return list;
}
//1.Consumer<T> :消费型接口
//void accept(T t)
@Test
public void test1(){
happyNight(500, s -> {
System.out.println("学习很辛苦,累了的话,可以去正规的足浴店放松一下。花费:" + s);
});
}
public void happyNight(int count, Consumer<Integer> consumer){
consumer.accept(count);
}
}
总结:从方法的角度来说:
1.方法在调用时,如果发现方法的形参是一个函数型接口,那么我们调用此方法时,可以使用lambda表达式
作为实参传递给此接口形参
2.方法定义时,如果需要一个定义接口,且此接口只有一个抽象方法,(说明此接口就是函数式接口),那么
考虑是有有现成的函数式接口可用。如果有,则不需要我们再去定义。比如:FilterData 替换为Predicate
构造器引用
一、构造器引用
1.格式: 类名 :: new
2.要求:函数式接口中抽象方法的形参列表与构造器形参列表一致(类型相同,个数相同),
同时,抽象方法的返回值类型即为构造器所属的类的类型。
public class ConstructorRefTest {
@Test
public void test4(){
Function<Integer,String[]> func1 = (length) -> new String[length];
String[] arr = func1.apply(10);
System.out.println(arr.length);
System.out.println("**********");
Function<Integer,String[]> func2 = String[]::new;
String[] arr1 = func2.apply(20);
System.out.println(arr1.length);
}
@Test
public void test3(){
BiFunction<Integer,String,Employee> func1 = (id,name) -> new Employee(id,name);
Employee emp = func1.apply(10, "Jim");
System.out.println(emp);
System.out.println("**********");
BiFunction<Integer,String,Employee> func2 = Employee::new;
Employee emp1 = func2.apply(20, "Jim");
System.out.println(emp1);
}
@Test
public void test2(){
Function<Integer,Employee> func1 = (id) -> new Employee(id);
Employee emp1 = func1.apply(12);
System.out.println(emp1);
System.out.println("**********");
Function<Integer,Employee> func2 = Employee::new;
Employee emp2 = func2.apply(12);
System.out.println(emp2);
}
@Test
public void test1(){
Supplier<Employee> sup = () -> new Employee();
Employee emp = sup.get();
System.out.println(emp);
System.out.println("**********");
Supplier<Employee> sup1 = Employee::new;
Employee emp1 = sup1.get();
System.out.println(emp1);
}
}
方法引用的使用
1.方法引用可以看做是Lambda表达式深层次的表达,或者可以理解为:方法引用就是Lambda表达式。
又因为Lambda表达式本身就是函数式接口的实例,进而方法引用也可以看做函数式接口的实例。
2.使用情境:
当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
3.要求:函数式接口中抽象方法的形参列表和返回值类型 要与 方法引用对应的方法的形参列表和返回值类型一致!
4.格式:类(或 对象) :: 方法名
5.分为如下的三种情况:
① 对象 :: 实例方法
② 类 :: 静态方法
③ 类 :: 实例方法 (有难度)
6.在满足如上的第2条d的情况下,使用方法引用替换Lambda表达式。如果方法引用不熟悉,可以使用Lambda表达式。
public class MethodRefTest {
//情况三:类 :: 实例方法 (有难度)
//注意:当函数式接口方法的第一个参数是需要引用方法的调用者,
//并且第二个参数是需要引用方法的参数(或无参数)时:ClassName::methodName
@Test
public void test7(){
Employee emp = new Employee(1001, "Jerry", 32, 23430);
Function<Employee,String> func1 = (e) -> e.getName();
String name = func1.apply(emp);
System.out.println(name);
System.out.println("***************");
Function<Employee,String> func2 = Employee::getName;
String name1 = func2.apply(emp);
System.out.println(name1);
}
@Test
public void test6(){
BiPredicate<String,String> bi = (s1,s2) -> s1.equals(s2);
boolean b = bi.test("abc", "abc");
System.out.println(b);
System.out.println("***************");
BiPredicate<String,String> bi1 = String::equals;
boolean b1 = bi1.test("abc", "abc");
System.out.println(b1);
}
@Test
public void test5(){
Comparator<String> com = (s1,s2) -> s1.compareTo(s2);
int value = com.compare("abad", "abdd");
System.out.println(value);
System.out.println("***************");
Comparator<String> com1 = String::compareTo;
int value1 = com1.compare("aaaaaa", "aa");
System.out.println(value1);
}
//情况二:类 :: 静态方法
@Test
public void test4(){
Function<Double,Long> func1 = d -> Math.round(d);
Long value = func1.apply(12.3);
System.out.println(value);
System.out.println("***************");
Function<Double,Long> func2 = Math::round;
Long value1 = func2.apply(12.6);
System.out.println(value1);
Function<Long,Long> func3 = Math::abs;
Long value2 = func3.apply(-1234L);
System.out.println(value2);
}
@Test
public void test3(){
Comparator<Integer> com = (num1,num2) -> Integer.compare(num1,num2);
int value = com.compare(12, 32);
System.out.println(value);
System.out.println("***************");
Comparator<Integer> com1 = Integer::compare;
int value1 = com1.compare(43, 12);
System.out.println(value1);
}
//情况一:对象 :: 实例方法
@Test
public void test2(){
Employee emp = new Employee(1001, "Tom", 23, 4534);
Supplier<String> sup = () -> emp.getName();
String name = sup.get();
System.out.println(name);
System.out.println("***************");
Supplier<String> sup1 = emp::getName;
String name1 = sup1.get();
System.out.println(name1);
}
@Test
public void test1(){
Consumer<String> con1 = str -> System.out.println(str);
con1.accept("beijing");
System.out.println("***************");
PrintStream ps = System.out;
Consumer<String> con2 = ps :: println;
con2.accept("shanghai");
}
}
Stream API
1.Stream API:
可以理解为java提供的一套api,使用这套api可以实现对集合、数组中的数据进行过滤、映射、归约、查找等操作
2.注意点:
①Stream 自己不会存储元素。
②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。
3.Stream的使用流程:
步骤一:Stream的实例化
步骤二:一系列的中间操作
步骤三:终止操作
注意:①步骤二中的中间操作可以有多个
②如果没有终止操作,那么一系列的中间操作是不会执行的。只有执行了步骤三的终止操作,步骤二才会执行:惰性求值
③终止操作一旦执行,就不可以再执行中间操作或其他的终止操作。
步骤一:Stream的实例化
public class StreamAPITest {
//方式四:创建无限流
@Test
public void test4(){
// 迭代
// public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
Stream<Integer> stream = Stream.iterate(0, x -> x + 2);
stream.limit(10).forEach(System.out::println);
// 生成
// public static<T> Stream<T> generate(Supplier<T> s)
Stream<Double> stream1 = Stream.generate(Math::random);
stream1.limit(10).forEach(System.out::println);
}
//方式三:Stream的静态方法of()
@Test
public void test3(){
//public static<T> Stream<T> of(T... values) : 返回一个流
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
}
//方式二:通过数组
@Test
public void test2(){
//调用Arrays的static <T> Stream<T> stream(T[] array): 返回一个流
String[] arr = new String[]{"MM","GG","JJ","DD"};
Stream<String> stream = Arrays.stream(arr);
}
//方式一:通过集合
@Test
public void test1(){
// default Stream<E> stream() : 返回一个顺序流
List<Employee> list = EmployeeData.getEmployees();
Stream<Employee> stream = list.stream();
// default Stream<E> parallelStream() : 返回一个并行流
Stream<Employee> stream1 = list.parallelStream();
}
}
步骤二:测试中间操作
1.可以通过Stream的实例,执行多次中间操作
2.中间操作,只有在执行了终止操作以后才会执行。
public class StreamAPITest1 {
//3-排序
@Test
public void test4(){
// sorted()——自然排序
List<Integer> list = Arrays.asList(23,43,454,32,1,2,5,5,-8);
list.stream().sorted().forEach(System.out::println);
//此时针对Employees进行排序:失败。原因:Employee类没有实现Comparable接口
// List<Employee> list1 = EmployeeData.getEmployees();
// list1.stream().sorted().forEach(System.out::println);
// sorted(Comparator com)——定制排序
List<Employee> list1 = EmployeeData.getEmployees();
list1.stream().sorted((e1,e2) -> {
if(e1.getAge() != e2.getAge()){
return e1.getAge() - e2.getAge();
}else{
return -Double.compare(e1.getSalary(),e2.getSalary());
}
}).forEach(System.out::println);
}
@Test
public void test3(){
ArrayList list1 = new ArrayList();
list1.add(1);
list1.add(2);
list1.add(3);
ArrayList list2 = new ArrayList();
list2.add(4);
list2.add(5);
list2.add(6);
// list1.add(list2); ---map()
// System.out.println(list1);//[1, 2, 3, [4, 5, 6]]
// list1.addAll(list2); -- flatMap()
// System.out.println(list1);//[1, 2, 3, 4, 5, 6]
}
//2-映射
@Test
public void test2(){
// map(Function f)——接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素。
List<String> list = Arrays.asList("aa","bb","cc","dd");
list.stream().map(String::toUpperCase).forEach(System.out::println);
// 练习:获取员工姓名长度大于3的员工的姓名。
Stream<Employee> stream = EmployeeData.getEmployees().stream();
Stream<String> stream1 = stream.map(Employee::getName);
stream1.filter(name -> name.length() > 3).forEach(System.out::println);
Stream<Stream<Character>> stream2 = list.stream().map(StreamAPITest1::fromStringToChar);
stream2.forEach(
x ->{
x.forEach(System.out::println);
}
);
System.out.println();
// flatMap(Function f)——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
Stream<Character> stream3 = list.stream().flatMap(StreamAPITest1::fromStringToChar);
stream3.forEach(System.out::println);
}
//将str中的字符存在集合中,返回集合的Stream
public static Stream<Character> fromStringToChar(String str){
ArrayList<Character> list = new ArrayList<>();
// for(Character c : str.toCharArray()){
// list.add(c);
// }
for(int i = 0;i < str.length();i++){
list.add(str.charAt(i));
}
return list.stream();
}
//1-筛选与切片
@Test
public void test1(){
List<Employee> list = EmployeeData.getEmployees();
//体会方法链的调用方式。比如:StringBuffer s = new StringBuffer(); s.append("A").append("B");
// filter(Predicate p)——接收 Lambda , 从流中排除某些元素。
Stream<Employee> stream = list.stream().filter(e -> e.getAge() > 30);
stream.forEach(System.out::println);
System.out.println();
// limit(n)——截断流,使其元素不超过给定数量。
list.stream().filter(e -> e.getAge() > 30).limit(3).forEach(System.out::println);
System.out.println();
// skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
list.stream().filter(e -> e.getAge() > 30).skip(3).forEach(System.out::println);
System.out.println();
// distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
list.add(new Employee(1009,"刘强东",30,6000));
list.add(new Employee(1009,"刘强东",30,6000));
list.add(new Employee(1009,"刘强东",30,6000));
list.add(new Employee(1009,"刘强东",30,6000));
list.add(new Employee(1009,"刘强东",30,6000));
list.stream().distinct().forEach(System.out::println);
}
}
步骤三:终止操作
public class StreamAPITest2 {
//3-收集:将集合--->Stream --->集合
@Test
public void test5(){
// collect(Collector c)——将流转换为其他形式。接收一个 Collector接口的实现,
// 用于给Stream中元素做汇总的方法
List<Employee> list = EmployeeData.getEmployees();
List<Employee> list1 = list.stream().filter(e -> e.getSalary() > 5000).collect(Collectors.toList());
//遍历
list1.forEach(System.out::println);
System.out.println();
Set<Employee> set = list.stream().filter(e -> e.getSalary() > 5000).collect(Collectors.toSet());
set.forEach(System.out::println);
System.out.println();
ArrayList<Employee> list2 = list.stream().filter(e -> e.getSalary() > 5000).collect(Collectors.toCollection(ArrayList::new));
for (Employee employee : list2) {
System.out.println(employee);
}
}
//2-归约
@Test
public void test4(){
// reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
// Integer sum = list.stream().reduce(0, (x1, x2) -> x1 + x2);
Integer sum = list.stream().reduce(10, Integer::sum);
System.out.println(sum);
// reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
// 练习1:计算公司所有员工工资的总和
List<Employee> emps = EmployeeData.getEmployees();
Stream<Double> moneyStream = emps.stream().map(Employee::getSalary);
Optional<Double> moneyOptional = moneyStream.reduce(Double::sum);
System.out.println(moneyOptional.get());
// 练习2:员工姓名中包含“马”字的个数
Stream<String> nameStream = emps.stream().map(Employee::getName);
Stream<Character> charStream = nameStream.flatMap(StreamAPITest1::fromStringToChar);
//方式一:
// long count = charStream.filter(c -> c.equals('马')).count();
// System.out.println(count);
//方式二:
Optional<Integer> op = charStream.map(c -> {
if (c.equals('马')) {
return 1;
} else {
return 0;
}
}).reduce(Integer::sum);
System.out.println(op.get());
//练习3:员工姓名中包含“马”的员工个数
long count = emps.stream().map(Employee::getName).filter(name -> name.contains("马")).count();
System.out.println(count);
// 练习4:员工姓名中包含“马”的员工的姓名
emps.stream().map(Employee::getName).filter(name -> name.contains("马")).forEach(System.out::println);
}
//1-匹配与查找
@Test
public void test2(){
List<Employee> list = EmployeeData.getEmployees();
// max(Comparator c)——返回流中最大值
// 练习:返回最高的工资:
Stream<Employee> stream = list.stream();
Stream<Double> stream1 = stream.map(Employee::getSalary);
Optional<Double> max = stream1.max(Double::compare);
System.out.println(max.get());
// min(Comparator c)——返回流中最小值
// 练习:返回最低工资的员工
Stream<Employee> stream2 = list.stream();
Optional<Employee> min = stream2.min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(min.get());
// forEach(Consumer c)——内部迭代
list.stream().forEach(System.out::println);
}
//外部迭代
@Test
public void test3(){
List<Employee> list = EmployeeData.getEmployees();
Iterator<Employee> iterator = list.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
@Test
public void test1(){
List<Employee> list = EmployeeData.getEmployees();
// allMatch(Predicate p)——检查是否匹配所有元素
//是否所有的员工的年龄都大于18
boolean b = list.stream().allMatch(e -> e.getAge() > 18);
System.out.println(b);
// anyMatch(Predicate p)——检查是否至少匹配一个元素
//是否存在员工的工资大于 10000
boolean b1 = list.stream().anyMatch(e -> e.getSalary() > 9900);
System.out.println(b1);
// noneMatch(Predicate p)——检查是否没有匹配的元素
//是否存在员工姓“雷”
boolean b2 = list.stream().noneMatch(e -> e.getName().contains("雷"));
System.out.println(b2);
// findFirst——返回第一个元素
Optional<Employee> emp = list.stream().sorted((e1,e2) -> {
if(e1.getAge() != e2.getAge()){
return e1.getAge() - e2.getAge();
}else{
return -Double.compare(e1.getSalary(),e2.getSalary());
}
}).findFirst();
System.out.println(emp.get());
// findAny——返回当前流中的任意元素
Optional<Employee> emp1 = list.parallelStream().findAny();
System.out.println(emp1.get());
// count——返回流中元素的总个数
long count = list.stream().filter(e -> e.getSalary() > 5000).count();
System.out.println(count);
}
}