1.为什么要用lambda表达式
package com.atguigu.java8; public class Employee { private int id; private String name; private int age; private double salary; public Employee() { } public Employee(String name) { this.name = name; } public Employee(String name, int age) { this.name = name; this.age = age; } public Employee(int id, String name, int age, double salary) { this.id = id; this.name = name; this.age = age; this.salary = 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 String show() { return "测试方法引用!"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); long temp; temp = Double.doubleToLongBits(salary); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee) obj; if (age != other.age) return false; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary)) return false; return true; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + "]"; } }
优化方式一:策略设计模式需要的类
package com.atguigu.java8; @FunctionalInterface public interface MyPredicate<T> { public boolean test(T t); }
package com.atguigu.java8; public class FilterEmployeeForSalary implements MyPredicate<Employee> { @Override public boolean test(Employee t) { return t.getSalary() >= 5000; } } -------------------------------------------- package com.atguigu.java8; public class FilterEmployeeForAge implements MyPredicate<Employee>{ @Override public boolean test(Employee t) { return t.getAge() <= 35; } }
package com.atguigu.java8; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.TreeSet; import org.junit.Test; public class TestLambda1 { //原来的匿名内部类 @Test public void test1(){ Comparator<String> com = new Comparator<String>(){ @Override public int compare(String o1, String o2) { return Integer.compare(o1.length(), o2.length()); } }; TreeSet<String> ts = new TreeSet<>(com); TreeSet<String> ts2 = new TreeSet<>(new Comparator<String>(){ @Override public int compare(String o1, String o2) { return Integer.compare(o1.length(), o2.length()); } }); } //现在的 Lambda 表达式 @Test public void test2(){ Comparator<String> com = (x, y) -> Integer.compare(x.length(), y.length()); TreeSet<String> ts = new TreeSet<>(com); } List<Employee> emps = Arrays.asList( new Employee(101, "张三", 18, 9999.99), new Employee(102, "李四", 59, 6666.66), new Employee(103, "王五", 28, 3333.33), new Employee(104, "赵六", 8, 7777.77), new Employee(105, "田七", 38, 5555.55) ); //需求:获取公司中年龄小于 35 的员工信息 public List<Employee> filterEmployeeAge(List<Employee> emps){ List<Employee> list = new ArrayList<>(); for (Employee emp : emps) { if(emp.getAge() <= 35){ list.add(emp); } } return list; } @Test public void test3(){ List<Employee> list = filterEmployeeAge(emps); for (Employee employee : list) { System.out.println(employee); } } //需求:获取公司中工资大于 5000 的员工信息 public List<Employee> filterEmployeeSalary(List<Employee> emps){ List<Employee> list = new ArrayList<>(); for (Employee emp : emps) { if(emp.getSalary() >= 5000){ list.add(emp); } } return list; } //优化方式一:策略设计模式 public List<Employee> filterEmployee(List<Employee> emps, MyPredicate<Employee> mp){ List<Employee> list = new ArrayList<>(); for (Employee employee : emps) { if(mp.test(employee)){ list.add(employee); } } return list; } @Test public void test4(){ List<Employee> list = filterEmployee(emps, new FilterEmployeeForAge()); for (Employee employee : list) { System.out.println(employee); } System.out.println("------------------------------------------"); List<Employee> list2 = filterEmployee(emps, new FilterEmployeeForSalary()); for (Employee employee : list2) { System.out.println(employee); } } //优化方式二:匿名内部类 @Test public void test5(){ List<Employee> list = filterEmployee(emps, new MyPredicate<Employee>() { @Override public boolean test(Employee t) { return t.getId() <= 103; } }); for (Employee employee : list) { System.out.println(employee); } } //优化方式三:Lambda 表达式 @Test public void test6(){ List<Employee> list = filterEmployee(emps, (e) -> e.getAge() <= 35); list.forEach(System.out::println); System.out.println("------------------------------------------"); List<Employee> list2 = filterEmployee(emps, (e) -> e.getSalary() >= 5000); list2.forEach(System.out::println); } //优化方式四:Stream API @Test public void test7(){ emps.stream() .filter((e) -> e.getAge() <= 35) .forEach(System.out::println); System.out.println("----------------------------------------------"); emps.stream() .map(Employee::getName) .limit(3) .sorted() .forEach(System.out::println); } }
2.lambda基础语法
package com.atguigu.java8; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import org.junit.Test; /* * 一、Lambda 表达式的基础语法:Java8中引入了一个新的操作符 "->" 该操作符称为箭头操作符或 Lambda 操作符 * 箭头操作符将 Lambda 表达式拆分成两部分: * * 左侧:Lambda 表达式的参数列表 * 右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体 * * 语法格式一:无参数,无返回值 * () -> System.out.println("Hello Lambda!"); * * 语法格式二:有一个参数,并且无返回值 * (x) -> System.out.println(x) * * 语法格式三:若只有一个参数,小括号可以省略不写 * x -> System.out.println(x) * * 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句 * Comparator<Integer> com = (x, y) -> { * System.out.println("函数式接口"); * return Integer.compare(x, y); * }; * * 语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写 * Comparator<Integer> com = (x, y) -> Integer.compare(x, y); * * 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断” * (Integer x, Integer y) -> Integer.compare(x, y); * * 上联:左右遇一括号省 * 下联:左侧推断类型省 * 横批:能省则省 * * 二、Lambda 表达式需要“函数式接口”的支持 * 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰 * 可以检查是否是函数式接口 */ public class TestLambda2 { @Test public void test1(){ int num = 0;//jdk 1.7 前,必须是 final Runnable r = new Runnable() { @Override public void run() { System.out.println("Hello World!" + num); } }; r.run(); System.out.println("-------------------------------"); Runnable r1 = () -> System.out.println("Hello Lambda!"); r1.run(); } @Test public void test2(){ Consumer<String> con = x -> System.out.println(x); con.accept("我大尚硅谷威武!"); } @Test public void test3(){ Comparator<Integer> com = (x, y) -> { System.out.println("函数式接口"); return Integer.compare(x, y); }; } @Test public void test4(){ Comparator<Integer> com = (x, y) -> Integer.compare(x, y); } @Test public void test5(){ // String[] strs; // strs = {"aaa", "bbb", "ccc"}; List<String> list = new ArrayList<>(); show(new HashMap<>()); } public void show(Map<String, Integer> map){ } //需求:对一个数进行运算 @Test public void test6(){ Integer num = operation(100, (x) -> x * x); System.out.println(num); System.out.println(operation(200, (y) -> y + 200)); } public Integer operation(Integer num, MyFun mf){ return mf.getValue(num); } }
需要的函数式接口
package com.atguigu.java8; //函数式接口 @FunctionalInterface public interface MyFun { public Integer getValue(Integer num); }
3.练习
package com.atguigu.exer; @FunctionalInterface public interface MyFunction { public String getValue(String str); }
package com.atguigu.exer; public interface MyFunction2<T, R> { public R getValue(T t1, T t2); }
package com.atguigu.exer; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import com.atguigu.java8.Employee; public class TestLambda { List<Employee> emps = Arrays.asList( new Employee(101, "张三", 18, 9999.99), new Employee(102, "李四", 59, 6666.66), new Employee(103, "王五", 28, 3333.33), new Employee(104, "赵六", 8, 7777.77), new Employee(105, "田七", 38, 5555.55) ); //1.调用Collections.sort() 方法,通过定制排序比较两个Employee (先按年龄比,年龄相同按姓名比),使用Lambda作为参数传递。 @Test public void test1(){ Collections.sort(emps, (e1, e2) -> { if(e1.getAge() == e2.getAge()){ return e1.getName().compareTo(e2.getName()); }else{ return -Integer.compare(e1.getAge(), e2.getAge()); } }); for (Employee emp : emps) { System.out.println(emp); } } //2.①声明函数式接口, 接口中声明抽象方法,public String getValue(String str); //②声明类TestLambda,类中编写方法使用接口作为参数,将一个字符串转换成大写,并作为方法的返回值。。 //③再将一个字符串的第2个和第4个索引位置进行藏取子串。。 @Test public void test2(){ String trimStr = strHandler("\t\t\t 我大尚硅谷威武 ", (str) -> str.trim()); System.out.println(trimStr); String upper = strHandler("abcdef", (str) -> str.toUpperCase()); System.out.println(upper); String newStr = strHandler("我大尚硅谷威武", (str) -> str.substring(2, 5)); System.out.println(newStr); } //需求:用于处理字符串 public String strHandler(String str, MyFunction mf){ return mf.getValue(str); } //3.①声明一个带两个泛型的函数式接口,泛型类型为<T, RP τT为参数,R为返回值。 //②接口中声明对应抽象方法。 //③在TestLambda 类中声明方法,使用接口作为参数,计算两个long 型参数的和。。 //④再计算两个long 型参数的乘积。 @Test public void test3(){ op(100L, 200L, (x, y) -> x + y); op(100L, 200L, (x, y) -> x * y); } //需求:对于两个 Long 型数据进行处理 public void op(Long l1, Long l2, MyFunction2<Long, Long> mf){ System.out.println(mf.getValue(l1, l2)); } }