javaJSE---Lambda表达式

本文深入探讨了Java中的Lambda表达式,包括其基本概念、使用方法、函数式接口的原理,并通过多个示例(如Demo1到Demo4,LambdaInterface,Student, Teacher等)详细阐述了Lambda在实际开发中的应用。同时,文章还解释了为何要使用Lambda表达式及其背后的思考(why1至why4部分)。" 50612737,5550315,iOS Touch ID技术解析与应用,"['iOS开发', 'Touch ID', '指纹认证', 'LocalAuthentication']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本章概述:本章主要讲了Lambda表达式在Java中的使用,Lambda表达式的介绍,Lambda表达式的使用,函数式接口,Lambda表达式的原理。

本章概述:

一、funtionref

1)Demo1

2)Demo2

3)Demo3

4)Demo4

二、lambda

1)LambdaInterface

2)LambdaTest

3)Student

4)StudentDao

5)Teacher

6)TeacherDao

三、why1

1)Student

2)Test

四、why2

1)AgrFilter

2)ScoreFilter

3)StudentFilter

4)Test

五、why3

1)Test

六、why4

1)Test

七、LambdaDemo

八、LambdaInterface

-----------------------------------------------------------------------------------------------------------------------------

一、funtionref

1)Demo1.java

public class Demo1 {

    static String put(){
        System.out.println("put... ...");
        return "put";
    }
    public static void getNum(int num){
        System.out.println("num:"+num);
    }
    public static String toUpperCase(String str){
        return str.toUpperCase();
    }
    public static Integer getStrLength(String str1,String str2){
        return str1.length()+str2.length();
    }

    public static void main(String[] args) {
        System.out.println(put());

        Supplier<String> s1 =()->Demo1.put();
        Supplier<String> s2 =()->{return Demo1.put();};
        Supplier<String> s3 =Demo1::put;
        System.out.println(s1.get());
        System.out.println(s2.get());
        System.out.println(s3.get());


        Consumer<Integer> consumer1 = (num)->Demo1.getNum(num);
        Consumer<Integer> consumer2 = Demo1::getNum;
        consumer1.accept(200);
        consumer2.accept(300);

        Function<String,String> f1 = (str)->str.toUpperCase();
        Function<String,String> f2 = (str)->{return Demo1.toUpperCase(str);};
        Function<String,String> f3 = (str)->Demo1.toUpperCase(str);
        Function<String,String> f4 = Demo1::toUpperCase;
        Function<String,String> f5 = Fun::toUpperCase;
        System.out.println(f1.apply("abcdefg"));
        System.out.println(f2.apply("hijklmn"));
        System.out.println(f3.apply("opqrst"));
        System.out.println(f4.apply("uvw"));
        System.out.println(f5.apply("xyz"));


        BiFunction<String,String,Integer> b1 = Demo1::getStrLength;
        BiFunction<String,String,Integer> b2 = (a,b)->Demo1.getStrLength(a,b);
        BiFunction<String,String,Integer> b3 = (a,b)->{return Demo1.getStrLength(a,b);};
        System.out.println(b1.apply("45679","asffg"));
        System.out.println(b2.apply("45679","asffg"));
        System.out.println(b3.apply("45679","asffg"));
    }
}
class Fun{
    public static String toUpperCase(String str){
        return str.toUpperCase();
    }
}

2)Demo2.java

public class Demo2 {

    public void getNum(int num){
        System.out.println("num:"+num);
    }
    public String toUpperCase(String str){
        return str.toUpperCase();
    }
    public Integer getStrLength(String str1,String str2){
        return str1.length()+str2.length();
    }

    public static void main(String[] args) {
        new Demo2().getNum(10);

        Consumer<Integer> c1 =(num)->new Demo2().getNum(num);
        Consumer<Integer> c2 =(num)->{new Demo2().getNum(num);};
        Consumer<Integer> c3 = new Demo2()::getNum;
        c1.accept(123);
        c2.accept(123);
        c3.accept(123);

        Function<String,String> f1 = (str)->str.toUpperCase();
        Function<String,String> f2 = (str)->new Demo2().toUpperCase(str);
        Function<String,String> f3 = (str)->{return new Demo2().toUpperCase(str);};
        Function<String,String> f4 = new Demo2()::toUpperCase;
        System.out.println(f1.apply("sdfg"));
        System.out.println(f2.apply("sdfg"));
        System.out.println(f3.apply("sdfg"));
        System.out.println(f4.apply("sdfg"));

        BiFunction<String,String,Integer> bf1 = (str1,str2)->new Demo2().getStrLength(str1,str2);
        BiFunction<String,String,Integer> bf2 = (str1,str2)->{return new Demo2().getStrLength(str1,str2);};
        BiFunction<String,String,Integer> bf3 = new Demo2()::getStrLength;
        System.out.println(bf1.apply("454665", "sddvv"));
        System.out.println(bf2.apply("454665", "sddvv"));
        System.out.println(bf3.apply("454665", "sddvv"));
    }
}

3)Demo3.java

public class Demo3 {
    public static void main(String[] args) {
        Consumer<Too> c1 =(too)->new Too().foo();
//        Consumer<Too> c2 =(too)->new Too2().foo();  不常用
        Consumer<Too> c3 = Too::foo;
        c1.accept(new Too());
//        c2.accept(new Too());
        c3.accept(new Too());

        BiConsumer<Too2,Integer> bc1 = (too2,i)->new Too2().show(i);
        BiConsumer<Too2,Integer> bc2 =Too2::show;
        bc1.accept(new Too2(),233);
        bc2.accept(new Too2(),566);

        BiFunction<Exec,String,Integer> bf1 = (e,s)->new Exec().getNum(s);
        BiFunction<Exec,String,Integer> bf2 = Exec::getNum;
        System.out.println(bf1.apply(new Exec(), "123"));
        System.out.println(bf2.apply(new Exec(), "789"));

    }
}
class Exec{
    public int getNum(String str){
        return 1;
    }
}

class Too{
    public Integer get(String str){
        return 1;
    }

    public void foo(){
        System.out.println("foo----Too");
    }
}

class Too2{
    public Integer get(String str){
        return 1;
    }

    public void foo(){
        System.out.println("foo2----Too2");
    }

    public void show(int i){
        System.out.println("show:" + i);
    }
}

4)Demo4.java

public class Demo4 {

    public static void main(String[] args) {
        Supplier<Person> s1 = ()->new Person();
        s1.get();
        Supplier<Person> s2 = Person::new;
        s2.get();

        Supplier<ArrayList> s3 = ArrayList::new;
        Supplier<Set> s4 = HashSet::new;
        Supplier<Thread> s5 = Thread::new;
        Supplier<String> s6 = String::new;
//        Supplier<Integer> s7 = Integer::new;

        Supplier<Account> s8 = Account::new;
        s8.get();

        Function<Integer,Account> f1 = (i)->new Account(i);
        Function<Integer,Account> f2 = Account::new;
        f1.apply(24);
        f2.apply(22);

        Consumer<String> c1 =(name)->new Account(name);
        Consumer<String> c2 =Account::new;
        c1.accept("张一通");
        c2.accept("黄小凡");
    }
}
class Account{
    public Account(){
        System.out.println("Account的空构造方法被调用了... ...");
    }
    public Account(int age){
        System.out.println("Account的一个参数age的构造方法被调用了... ..."+age);
    }
    public Account(String name){
        System.out.println("Account的一个参数name的构造方法被调用了... ..."+name);
    }
}
class Person{
    public Person(){
        System.out.println("Person的空构造方法被调用了... ...");
    }
}

二、lambda

1)LambdaInterface.java

@FunctionalInterface
public interface LambdaInterface {

    int get(int num);
}

2)LambdaTest.java

public class LambdaTest {
    public static void main(String[] args) throws Exception {
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                System.out.println("running--1!");
//            }
//        };
//        runnable.run();
//        Runnable runnable1 = ()-> System.out.println("running--2!");
//        Runnable runnable2 = ()-> {
//            System.out.println("running--3!");
//        };
//        runnable1.run();
//        runnable2.run();
//
//        Callable<String> callable = new Callable<String>() {
//            public String call() throws Exception {
//                return "huang";
//            }
//        };
//        System.out.println(callable.call());
//
//        Callable<String> callable1 = ()->{return "huang2";};
//        Callable<String> callable2 = ()->"huang3";
//        System.out.println(callable1.call());
//        System.out.println(callable2.call());
//
//        StudentDao dao = new StudentDao() {
//            @Override
//            public void insert(Student student) {
//                System.out.println("插入第一个学生记录"+student);
//            }
//        };
//        dao.insert(new Student());
//        StudentDao dao1 = (student) -> System.out.println("插入第二个学生记录"+student);
//        StudentDao dao2 = (Student student)-> System.out.println("插入第三个学生记录"+student);
//        StudentDao dao3 = (student )->{
//            System.out.println("插入第四个学生记录"+student);
//        };
//        StudentDao dao4 = (Student student)->{
//            System.out.println("插入第五个学生记录"+student);
//        };
//        StudentDao dao5 = student -> System.out.println("插入第六个学生记录"+student);
//        StudentDao dao6 = student -> {
//            System.out.println("插入第七个学生记录"+student);
//        };
//
//        dao1.insert(new Student());
//        dao2.insert(new Student());
//        dao3.insert(new Student());
//        dao4.insert(new Student());
//        dao5.insert(new Student());
//        dao6.insert(new Student());
//
//        TeacherDao teacherDao = new TeacherDao() {
//            @Override
//            public int get(Teacher teacher) {
//                return 1;
//            }
//        };
//        System.out.println(teacherDao.get(new Teacher()));
//        TeacherDao teacherDao1 = (teacher)-> {return 2;};
//        TeacherDao teacherDao2 = (teacher)->3;
//        TeacherDao teacherDao3 = teacher -> {return 4;};
//        TeacherDao teacherDao4 = teacher->5;
//        System.out.println(teacherDao1.get(new Teacher()));
//        System.out.println(teacherDao2.get(new Teacher()));
//        System.out.println(teacherDao3.get(new Teacher()));
//        System.out.println(teacherDao4.get(new Teacher()));
//
//
//        /*
//         *     在JDK中,提供了一些代表输入和输出的接口,他们本身是没有什么意义的,
//         *      只是为了方便的使用lambda表达式来编写代码,从而获取对应的执行结果。
//         *
//         */
////        Supplier<Integer> supplier =new Supplier<Integer>() {
////            @Override
////            public Integer get() {
////                return 1;
////            }
////        };
//        Supplier<Integer> supplier = ()->1;
//        System.out.println(supplier.get());
//
//
////        Consumer<String> consumer = new Consumer<String>() {
////            @Override
////            public void accept(String s) {
////                System.out.println(s);
////            }
////        };
//        Consumer<String> consumer = (s)-> System.out.println(s);
//        consumer.accept("huang");
//
////        Function<Integer,String> function = new Function<Integer, String>() {
////            @Override
////            public String apply(Integer integer) {
////                return integer + "huang2";
////            }
////        };
//        Function<Integer,String> function = (i)->i+"huang3";
//        Function<Integer,String> function1 = (Integer i)->{return i+"huang4";};
//        System.out.println(function.apply(2003));
//        System.out.println(function1.apply(2002));
        BiFunction<String,String,Integer> bf = (a,b)->a.length()+b.length();
        System.out.println(bf.apply("张一通","很帅"));
        Runnable runnable1 = ()-> System.out.println(get());
        Runnable runnable2 = ()->{
          String str = find();
            System.out.println(str);
        };
        Runnable runnable3 = ()->exec();
//        Runnable runnable4 = ()->1;
//        Runnable runnable5 = ()->"OK";
        Runnable runnable6 = ()->get();
//        Runnable runnable7 =()-> true?1:2;
        runnable1.run();
        runnable2.run();
        runnable3.run();

        LambdaInterface li1 = new LambdaInterface() {
            @Override
            public int get(int num) {
                return num;
            }
        };
        System.out.println(li1.get(200));
//        LambdaInterface li2 = (num) ->get(num);
//        LambdaInterface li3 = (num)-> System.out.println(num);
//        LambdaInterface li4 = (num) -> {return get(num);};
        LambdaInterface li5 = (num)->{return num;};
        LambdaInterface li6 = (num)->num;
        LambdaInterface li7 = num->{return num;};
        LambdaInterface li8 = num -> num;
        System.out.println(li5.get(300));


        Function<Integer,Integer> function = (num)->num;
        System.out.println(function.apply(100));
        Consumer<Integer> consumer1 = (num)-> System.out.println(num);
        consumer1.accept(1000);
        Consumer<Integer> consumer2 = (num)->getNum(num);
        consumer2.accept(2000);


        Function<String,String> f1 = (str)->str.toUpperCase();
        Function<String,String> f2 = (str)->toUpperCase(str);
        System.out.println(f1.apply("abcdefg"));
        System.out.println(f2.apply("cdsefgggg"));



        BiFunction<String,String,Integer> biFunction1 = (a,b)->a.length()+b.length();
        System.out.println(biFunction1.apply("张一通", "真帅"));
        BiFunction<String,String,Integer> biFunction2 = (a,b)->getStrLength(a,b);
        System.out.println(biFunction2.apply("张一通", "非常帅"));
    }

    public static void getNum(int num){
        System.out.println(num);
    }
    public static String toUpperCase(String str){
        return str.toUpperCase();
    }
    public static Integer getStrLength(String str1,String str2){
        return str1.length()+str2.length();
    }
    public static int get(){
        return 1;
    }
    public static String find(){
        return "find";
    }
    public static void exec(){
        find();
    }
}

3)Student.java

public class Student {
}

4)StudentDao.java

public interface StudentDao {
    public void insert(Student student);
}

5)Teacher.java

public class Teacher{
}

 6)TeacherDao.java

public interface TeacherDao {

    public int get(Teacher teacher);
}

三、why1

1)Student.java

public class Student {
    private String name;
    private int age;
    private int score;

    public Student() {
    }

    public Student(String name, int age, int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    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 int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}

2)Test.java

public class Test {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("zhangfei",18,75));
        list.add(new Student("guanyu",20,70));
        list.add(new Student("zhaoyun",26,75));
        list.add(new Student("liubei",30,85));
        list.add(new Student("huangzhong",23,90));

        //查询年龄大于25岁学生的信息
        getByAge(list);
        System.out.println("******************************************");
        //查询成绩大于80学生的信息
        getByScore(list);
    }
    public static void getByAge(ArrayList<Student> students){
        ArrayList<Student> list = new ArrayList<>();
        for(Student student : students){
            if(student.getAge()>25){
                list.add(student);
            }
        }
        for(Student student : list){
            System.out.println(student);
        }
    }
    public static void getByScore(ArrayList<Student> students){
        ArrayList<Student> list = new ArrayList<>();
        for(Student student : students){
            if(student.getScore()>80){
                list.add(student);
            }
        }
        for(Student student : list){
            System.out.println(student);
        }
    }
}

四、why2

1)AgeFilter.java

public class AgeFilter implements StudentFilter{

    @Override
    public boolean compare(Student student) {
        return student.getAge() > 25;
    }
}

2)ScoreFilter.java

public class ScoreFilter implements StudentFilter{
    @Override
    public boolean compare(Student student) {
        return student.getScore() > 80;
    }
}

3)StudentFilter.java

public interface StudentFilter {
    public boolean compare(Student student);
}

4)Test.java

public class Test {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("zhangfei",18,69));
        list.add(new Student("guanyu",20,70));
        list.add(new Student("zhaoyun",26,75));
        list.add(new Student("liubei",30,85));
        list.add(new Student("huangzhong",23,90));

        //查询年龄大于25岁的学生信息
        getByFilter(list,new AgeFilter());
        //查询分数大于80分的学生信息
        System.out.println("**************************************************");
        getByFilter(list,new ScoreFilter());
    }
    public static void getByFilter(ArrayList<Student> students,StudentFilter filter){
        ArrayList<Student> list = new ArrayList<>();
        for(Student student : students){
            if(filter.compare(student)){
                list.add(student);
            }
        }
        for(Student student :list){
            System.out.println(student);
        }
    }
}

五、why3

1)Test.java

public class Test {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("zhangfei",18,69));
        list.add(new Student("guanyu",20,70));
        list.add(new Student("zhaoyun",26,75));
        list.add(new Student("liubei",30,85));
        list.add(new Student("huangzhong",23,90));

        //查询年龄大于25岁的学生信息
        getByFilter(list, new StudentFilter() {
            @Override
            public boolean compare(Student student) {
                return student.getAge()>25;
            }
        });
        //查询成绩大于80分的学生信息
        System.out.println("************************************");
        getByFilter(list, new StudentFilter() {
            @Override
            public boolean compare(Student student) {
                return student.getScore()>80;
            }
        });
        //查询名字长度大于6的学生信息
        getByFilter(list, new StudentFilter() {
            @Override
            public boolean compare(Student student) {
                return student.getName().length() > 6;
            }
        });
    }
    public static void getByFilter(ArrayList<Student> students, StudentFilter filter){
        ArrayList<Student> list = new ArrayList<>();
        for(Student student : students){
            if(filter.compare(student)){
                list.add(student);
            }
        }
        for(Student student : list){
            System.out.println(student);
        }
    }
}

六、why4

1)Test.java

public class Test {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("zhangfei",18,69));
        list.add(new Student("guanyu",20,70));
        list.add(new Student("zhaoyun",26,75));
        list.add(new Student("liubei",30,85));
        list.add(new Student("huangzhong",23,90));

        //查询年龄大于25岁的学生信息
        getByFilter(list,(student -> student.getAge()>25));
        //查询成绩大于80分的学生信息
        System.out.println("***************************************");
        getByFilter(list,(student -> student.getScore()>80));
        //查询姓名长度大于6的学生成绩
        System.out.println("***************************************");
        getByFilter(list,(student) ->student.getName().length()>6 );

    }
    public static void getByFilter(ArrayList<Student> students, StudentFilter filter){
        ArrayList<Student> list = new ArrayList<>();
        for(Student student : students){
            if(filter.compare(student)){
                list.add(student);
            }
        }
        for(Student student :list){
            System.out.println(student);
        }
    }
}

七、LambdaDemo.java

public class LambdaDemo {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Running!");
            }
        });
        thread.start();


        new Thread(()-> System.out.println("Running!")).start();

        List<String> list = Arrays.asList("java","go","python","scala","javascript");
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.length()-o2.length();
            }
        });
        for(String str : list){
            System.out.println(str);
        }
        Collections.sort(list,(a,b)->a.length()-b.length());
        list.forEach(System.out::println);
    }
}

八、LambdaInterface.java

@FunctionalInterface
public interface LambdaInterface {
    public void add(int a,int b);

//    public void sub(int a,int b);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值