@Testpublic void test02(){// Lambda 表达式Comparator<Integer> comparator = (a, b) -> Integer.compare(a, b);TreeSet<Integer> set = new TreeSet<>(comparator);}
演变过程:
- 垃圾代码 —> 策略模式 —> 匿名内部类 —> Lambda表达式
口诀:
- 写死小括号,拷贝右箭头,落地大括号
- 左右遇一括号省
- 左侧推断类型省
1.lambda表达式的基础语法:
Java8中引入了一个新的操作符”->”,该操作符称为箭头操作符或者lambda操作符,箭头操作符将lambda表达式拆分成两部分:
左侧:lambda表达式的参数列表
右侧:lambda表达式中所需执行的功能,即lambda体。
2.语法格式:
1.无参数,无返回值
()->System.out.println(“Hello Lambda!”);
@Testpublic void test1() {int num = 0;//jdk1.7前,必须是final,但实质还是 final修饰Runnable r1 = new Runnable() {@Overridepublic void run() {System.out.println("Hello World!" + num);}};r1.run();System.out.println("---------------------------------------");Runnable r2 = () -> System.out.println("Hello Lambda!");r2.run();}
2.有一个参数,无返回值
@Testpublic void test2() {Consumer<String> consumer = (x) -> System.out.println(x);consumer.accept("我是家里蹲毕业!");}
3.若只有一个参数,小括号可以省略不写
@Testpublic void test2() {Consumer<String> consumer = x -> System.out.println(x);consumer.accept("我是家里蹲毕业!");}
4.有两个以上的参数,有返回值,并且lambda体中有多条语句
@Testpublic void test3() {Comparator<Integer> comparator = (x, y) -> {System.out.println("函数式接口");return Integer.compare(x, y);};System.out.println(comparator.compare(1, 3));}
5.若lambda体中只有一条语句,return和大括号都可以省略不写
@Testpublic void test4() {Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);System.out.println(comparator.compare(1, 3));}
6.lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出数据类型,即“类型推断”
3.lambda表达式需要函数式接口的支持:
函数式接口:
接口中只有一个抽象方法的接口,称为函数式接口。可以使用注解@FunctionalIterface修饰一下,可以检查是否为函数式接口。
2.测试:
@FunctionalInterfacepublic interface MyFun {public Integer getValue(Integer integer);}public Integer operation(Integer num, MyFun mf) {return mf.getValue(num);}@Testpublic void test6() {Integer operation = operation(100, (x) -> x * 2);System.out.println(operation);}
4.lambda案例
1.调用 Collections.sort() 方法,通过定制排序 比较两个 Employee (先按照年龄比,年龄相同按照姓名比),使用 Lambda 表达式作为参数传递
//员工集合List<Employee> employeeList = Arrays.asList(new Employee("张三", 18, 6669.58),new Employee("李四", 12, 7779.58),new Employee("王五", 36, 9229.58),new Employee("赵六", 51, 19999.58),new Employee("田七", 20, 3399.58));@Testpublic void test1() {Collections.sort(employeeList, (e1, e2) -> {if (e1.getAge() == e2.getAge()) {return e1.getName().compareTo(e2.getName());} else {return Integer.compare(e1.getAge(), e2.getAge());}});for (Employee employee : employeeList) {System.out.println(employee);}}
2.声明函数式接口,接口中声明抽象方法,String getValue(String str); 声明类 TestLambda,类中编写方法使用接口作为参数,将一个字符串转换成大写,并作为方法的返回值;再将一个字符串的第二个和第四个索引位置进行截取字串
@FunctionalInterfacepublic interface MyFunction {public String getValue(String string);}public String strHandler(String string, MyFunction mf) {return mf.getValue(string);}@Testpublic void test2() {System.out.println(strHandler("sjdsjdka", (x) -> x.toUpperCase()));System.out.println(strHandler("sjdsjdka", (x) -> x.substring(2, 4)));}
3.声明一个带两个泛型的函数式接口,泛型类型为
T 为参数,R 为返回值;接口中声明对应的抽象方法;在 TestLambda 类中声明方法,使用接口作为参数,计算两个 Long 类型参数的和;在计算两个 Long 类型参数的乘积 @FunctionalInterfacepublic interface MyFunction<T, R> {public R getValue(T t1, T t2);}public void getHandler(Long l1, Long l2, MyFunction<Long, Long> mf) {System.out.println(mf.getValue(l1, l2));}@Testpublic void test3() {getHandler(30L, 20L, (x, y) -> x + y);getHandler(30L, 20L, (x, y) -> x * y);}
5.函数式接口
| 函数式接口 | 参数类型 | 返回类型 | 用途 | | —- | —- | —- | —- | | Consumer
消费型接口 | T | void | 对类型为T的对象应用操作:void accept(T t) | | Supplier
提供型接口 | 无 | T | 返回类型为T的对象:T get() | | Function
函数型接口 | T | R | 对类型为T的对象应用操作,并返回结果为R类型的对象:R apply(T t) | | Predicate
断言型接口 | T | boolean | 确定类型为T的对象是否满足某约束,并返回boolean值:boolean test(T t) |
1.Consumer:消费型接口 void accept(T t);
@Testpublic void test() {happy(30000, (x) -> System.out.println("你们刚哥喜欢大保健,每次消费:" + x + "元"));}public void happy(double money, Consumer<Double> consumer) {consumer.accept(money);}
2.Supplier:提供型接口 T get();
@Testpublic void test1() {System.out.println(getNumList(10, () -> (int) (Math.random() * 100)));}//随机产生指定个数的整数,并放入集合中public List<Integer> getNumList(int num, Supplier<Integer> supplier) {List<Integer> list = new ArrayList<>();for (int i = 0; i < num; i++) {Integer integer = supplier.get();list.add(integer);}return list;}
3.Function:函数型接口 R apply(T t);
@Testpublic void test3() {System.out.println(strHandler("jalasjd", (x) -> x.toUpperCase()));}//需求:用于处理字符串public String strHandler(String string, Function<String, String> function) {return function.apply(string);}
4.Predicate:断言型接口 boolean test(T t);
@Testpublic void test4() {List<String> list = Arrays.asList("2112", "2123123", "3423432", "435345");System.out.println(filterStr(list, (x) -> x.contains("2")));}//断言型接口public List<String> filterStr(List<String> list, Predicate<String> predicate) {List<String> returnList = new ArrayList<>();for (int i = 0; i < list.size(); i++) {if (predicate.test(list.get(i))) {returnList.add(list.get(i));}}return returnList;}
5.其他接口
6.方法引用和构造器引用
1.方法引用:
若Lambda体中的内容有方法已经实现了,我们可以使用 “方法引用”(可以理解为方法引用是Lambda表达式的另外一种表现形式)
主要有三种语法格式:
1.对象::实例方法名
@Testpublic void test1() {Consumer<String> consumer = x -> System.out.println(x);PrintStream printStream = System.out;Consumer<String> consumer1 = printStream::println;Consumer<String> consumer2 = System.out::println;consumer2.accept("atguigu NB");}@Testpublic void test2() {Employee employee = new Employee();Supplier<String> supplier = () -> employee.getName();System.out.println(supplier.get());Supplier<Integer> supplier1 = employee::getAge;System.out.println(supplier1.get());}
注意:
- Lambda体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数列表和返回值类型保持一致。
2.类::静态方法名
@Testpublic void test3() {Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);Comparator<Integer> comparator1 = Integer::compare;comparator1.compare(3, 5);}
3.类::实例方法名
@Testpublic void test4() {BiPredicate<String, String> biPredicate = (x, y) -> x.equals(y);BiPredicate<String, String> biPredicate1 = String::equals;System.out.println(biPredicate1.test("hahaha", "hahah"));}
注意:
若Lambda参数列表中的第一个参数是实例方法的调用者,而第二个参数是实例方法的参数时,可以使用ClassName::method
2.构造器引用:
格式:ClassName::new
@Testpublic void test5() {Supplier<Employee> supplier = () -> new Employee("ha", 20, 30);Employee employee = supplier.get();System.out.println(employee);Supplier<Employee> supplier1 = Employee::new;Employee employee1 = supplier1.get();System.out.println(employee1);}@Testpublic void test6() {Function<Integer, Employee> function = (x) -> new Employee(x);System.out.println(function.apply(20));Function<Integer, Employee> function1 = Employee::new;System.out.println(function1.apply(20));}
注意:
需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致。
3.数组引用:
格式:Type::new
@Testpublic void test7() {Function<Integer, String[]> function = (x) -> new String[x];String[] strings = function.apply(10);System.out.println(strings.length);Function<Integer, String[]> function1 = String[]::new;String[] strings1 = function1.apply(20);System.out.println(strings1.length);}
