赞
踩
注意: 函数式接口:接口中只有一个抽象方法。
(参数1,参数2): 抽象方法的参数
->: 分隔符
{}:表示抽象方法的实
- package com.demo01;
-
- /**
- * @Author Li Qinghua
- * @Create 2022/7/19 14:38
- */
- public class TestLambda {
- public static void main(String[] args) {
- //匿名内部类
- Runnable r1=new Runnable() {
- @Override
- public void run() {
- System.out.println("Runnable");
- }
- };
- Thread t1=new Thread(r1);
- t1.start();
-
-
- Runnable r2=()->{
- System.out.println("这是Lambda表达式的Runnable");
- };
- Thread t2=new Thread(r2);
- t2.start();
-
- Thread t3=new Thread(()->{
- System.out.println("这是Lambda表达式的匿名内部Runnable");
- });
- t3.start();
- }
- }
Thread 类需要 Runnable 接口作为参数,其中的抽象 run 方法是用来指定线程任务内容的核心
为了指定 run 的方法体,不得不需要 Runnable 接口的实现类
为了省去定义一个 Runnable 实现类的麻烦,不得不使用匿名内部类
必须覆盖重写抽象 run 方法,所以方法名称、方法参数、方法返回值不得不再写一遍,且不能写错
而实际上,似乎只有方法体才是关键所在。
这时可以使用lambda表示完成上面的要求。
前提:必须是函数式接口。
简化匿名内部类的使用,语法更加简单。
- package com.demo03;
-
- /**
- * @Author Li Qinghua
- * @Create 2022/7/19 15:34
- */
- public class TestSwim {
- public static void main(String[] args) {
- method(()-> System.out.println("在游泳"));
- }
-
- public static void method(Swim s){
- s.swim();
- }
- }
-
- @FunctionalInterface
- interface Swim{
- public void swim();
- }
下面举例演示 java.util.Comparator 接口的使用场景代码,其中的抽象方法定义为:
public abstract int compare(T o1, T o2);
当需要对一个对象集合进行排序时, Collections.sort 方法需要一个 Comparator 接口实例来指定排序的规则。
- package com.demo02;
-
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
-
- /**
- * @Author Li Qinghua
- * @Create 2022/7/19 15:08
- */
- public class TestStudentSort {
- public static void main(String[] args) {
- List<Student> list=new ArrayList<>();
- list.add(new Student("李MM",29,176));
- list.add(new Student("李PP",19,174));
- list.add(new Student("李AA",23,183));
- list.add(new Student("李RR",22,179));
-
- Comparator<Student> comparator=new Comparator<Student>() {
- @Override
- public int compare(Student o1, Student o2) {
- return o2.getAge()-o1.getAge();
- }
- };
-
- Collections.sort(list,comparator);
-
- for(Student s:list){
- System.out.println(s);
- }
-
- System.out.println("=================");
-
- Comparator<Student> comparator1=(Student s1,Student s2)->{
- return (int) (s2.getHigh()-s1.getHigh());
- };
-
- Collections.sort(list,comparator1);
- for(Student s:list){
- System.out.println(s);
- }
-
- System.out.println("============");
- Collections.sort(list,(o1,o2)-> o2.getAge()-o1.getAge());
- for(Student s:list){
- System.out.println(s);
- }
- }
- }
-
- class Student{
- private String name;
- private int age;
- private double high;
-
- @Override
- public String toString() {
- return "Student{" +
- "name='" + name + '\'' +
- ", age=" + age +
- ", high=" + high +
- '}';
- }
-
- public Student(String name, int age, double high) {
- this.name = name;
- this.age = age;
- this.high = high;
- }
-
- 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 getHigh() {
- return high;
- }
-
- public void setHigh(double high) {
- this.high = high;
- }
- }
内置函数式接口的由来
- public class Test03 {
-
- public static void main(String[] args) {
- Operater o=arr -> {
- int sum=0;
- for(int n:arr){
- sum+=n;
- }
- System.out.println("数组的和为:"+sum);
- };
-
- fun(o);
- }
-
- public static void fun(Operater operater){
- int[] arr={2,3,4,5,6,7,11};
- operater.getSum(arr);
- }
-
- }
- @FunctionalInterface
- interface Operater{
- //求数组的和
- public abstract void getSum(int[] arr);
- }
分析
我们知道使用Lambda表达式的前提是需要有函数式接口。而Lambda使用时不关心接口名,抽象方法名,只关心抽 象方法的参数列表和返回值类型。因此为了让我们使用Lambda方便,JDK提供了大量常用的函数式接口。
常见得函数式接口
java.util.function保存
有参数,无返回值。
- package edu.demo04;
-
- import java.util.function.Consumer;
-
- /**
- * @Author Li Qinghua
- * @Create 2022/7/19 20:36
- */
- public class Test01 {
- public static void main(String[] args) {
-
- Consumer<Integer[]> c=nums->{
- int sum=0;
- for(int n:nums){
- sum+=n;
- }
- System.out.println(sum);
- };
-
- method(c);
- }
-
- //调用某个方法时,该方法需要的参数为接口类型,这时就应该能想到使用lambda
- public static void method(Consumer<Integer[]> consumer){
- Integer[] arr={1,2,3,4,5};
- consumer.accept(arr);
- }
- }
T:表示返回结果的泛型
无参,想有返回结果的函数式接口时使用Supplier
T get();
- package edu.demo04;
-
- import java.util.function.Supplier;
-
- /**
- * @Author Li Qinghua
- * @Create 2022/7/19 20:59
- */
- public class Test02 {
- public static void main(String[] args) {
- method(()->{
- return "Hello World";
- });
- }
-
- public static void method(Supplier<String> supplier){
- String str = supplier.get();
- System.out.println(str);
- }
- }
T: 参数类型的泛型
R: 函数返回结果的泛型
有参,有返回 值时。
例子: 传入一个学生的姓名,求出该学生的年龄或者姓名。
- package edu.demo04;
-
- import java.util.function.Function;
-
- /**
- * @Author Li Qinghua
- * @Create 2022/7/19 21:04
- */
- public class Test03 {
- public static void main(String[] args) {
- Function<Student,Integer> function=(stu)->{
- return stu.getAge();
- };
-
- method(function);
- }
-
- public static void method(Function<Student,Integer> function){
- Integer age = function.apply(new Student("李QQ", 23));
- System.out.println(age);
- }
- }
-
- class Student{
- private String name;
- private int age;
-
- public Student(String name, int age) {
- this.name = name;
- this.age = age;
- }
-
- 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;
- }
-
- @Override
- public String toString() {
- return "Student{" +
- "name='" + name + '\'' +
- ", age=" + age +
- '}';
- }
- }
T: 参数的泛型
boolean test(T t);
当传入一个参数时,需要对该参数进行判断时,则需要这种函数。
- package com.demo07;
-
- import java.util.function.Predicate;
-
- /**
- * @Author Li Qinghua
- * @Create 2022/7/19 16:50
- */
- public class TestPredicated {
- public static void main(String[] args) {
- method(name->name.length()>3?true:false,"雷霆嘎巴");
- }
-
- public static void method(Predicate<String> predicate,String name){
-
- boolean b = predicate.test(name);
- System.out.println(b);
- }
- }
- package com.demo08;
-
- import java.util.function.Consumer;
-
- /**
- * @Author Li Qinghua
- * @Create 2022/7/19 19:04
- * lambda 冗余 静态方法引用
- */
- public class Test01 {
- public static void main(String[] args) {
- Consumer<Integer> c1=(num)->{
- int sum=0;
- for (int i = 0; i <= num; i++) {
- sum+=i;
- }
- System.out.println(sum);
- };
-
- method(c1,100);
-
- getSum(100);
- }
-
- public static void method(Consumer<Integer> consumer,Integer num){
- consumer.accept(num);
- }
-
- public static void getSum(Integer num){
- int sum=0;
- for (int i = 0; i <=num; i++) {
- sum+=i;
- }
- System.out.println("和为:"+sum);
- }
- }
分析:
如果我们在Lambda中所指定的功能,已经有其他方法存在相同方案,那是否还有必要再写重复逻辑?可以直接“引 用”过去就好了:---方法引用。
- package com.demo08;
-
- import java.util.function.Consumer;
-
- /**
- * @Author Li Qinghua
- * @Create 2022/7/19 19:04
- * lambda 冗余 静态方法引用
- */
- public class Test01 {
- public static void main(String[] args) {
- /*Consumer<Integer> c1=(num)->{
- int sum=0;
- for (int i = 0; i <= num; i++) {
- sum+=i;
- }
- System.out.println(sum);
- };*/
- Consumer<Integer> c2=Test01::getSum;
-
- //method(c1,100);
- method(c2,100);
- //getSum(100);
- }
-
- public static void method(Consumer<Integer> consumer,Integer num){
- consumer.accept(num);
- }
-
- public static void getSum(Integer num){
- int sum=0;
- for (int i = 0; i <=num; i++) {
- sum+=i;
- }
- System.out.println("和为:"+sum);
- }
- }
请注意其中的双冒号 :: 写法,这被称为“方法引用”,是一种新的语法。
方法引用的分类
实例方法引用,顾名思义就是调用已经存在的实例的方法,与静态方法引用不同的是类要先实例化,静态方法引用类无需实例化,直接用类名去调用。
- package com.demo08;
-
- import java.util.function.Supplier;
-
- /**
- * @Author Li Qinghua
- * @Create 2022/7/19 19:30
- */
- public class Test03 {
- public static void main(String[] args) {
- /*Person[] people={new Person("李AA",19),new Person("李UU",23),new Person("李NN",21)
- new Person("李OO",16)};*/
- Person p=new Person("李AA",23);
- Supplier<String> supplier=p::getName;
-
- method(supplier);
- }
-
- public static void method(Supplier<String> supplier){
- String s = supplier.get();
- System.out.println(s);
- }
- }
-
- class Person{
- private String name;
- private int age;
-
- public static int compareTo(Person p1,Person p2){
- return p2.getAge()-p1.getAge();
- }
-
- @Override
- public String toString() {
- return "Person{" +
- "name='" + name + '\'' +
- ", age=" + age +
- '}';
- }
-
- 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 Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- }
-
类名::实例方法. (参数1,参数2)->参数1.实例方法(参数2)
- package edu.demo05;
-
- import java.util.function.BiFunction;
- import java.util.function.Consumer;
- import java.util.function.Function;
- import java.util.function.Supplier;
-
- /**
- * @Author Li Qinghua
- * @Create 2022/7/20 14:40
- */
- public class Test03 {
- public static void main(String[] args) {
- Function<String,Integer> function=String::length;
- Integer len = function.apply("abc");
- System.out.println(len);
-
- System.out.println("~~~~~~~~~~~");
-
- //比较两个字符串的内容是否一致.T, U, R
- BiFunction<String,String,Boolean> bi=String::equals;
- Boolean b = bi.apply("abc", "efg");
- System.out.println(b);
-
- System.out.println("~~~~~~~~~~");
-
- Function<String,People> function1=People::new;
- People person = function1.apply("李四");
- System.out.println(person);
- }
- }
-
- class People{
- private String name;
-
- public People() {
- }
-
- public People(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return "People{" +
- "name='" + name + '\'' +
- '}';
- }
- }
类名::new (参数)->new 类名(参数)
- Function<String,People> function1=People::new;
- People person = function1.apply("李四");
- System.out.println(person);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。