• Java之lambda表达式与函数式接口


    本节介绍了lambda表达式和匿名内部类,匿名内部类适用于接口,抽象类和具体类,而lambda表达式只能适用于接口,并且接口中只能有一个抽象方法。并且介绍了lambda表达式中类的方法引用、对象的方法引用,构造器的方法引用,最后介绍了常用的函数式接口Supplier,Consumer,Predicate,Function等,并对函数式接口的使用进行了练习。

    目录

    1、多线程实现方式体验lambda表达式

    2、lambda表达式练习(抽象方法无参无返回值)

    3、lambda表达式练习(抽象方法带参无返回值)

    4、lambda表达式练习(抽象方法带参带返回值)

    5、lambda表达式的中方法引用

    6、lambda表达式中的方法引用2

    7、lambda表达式引用对象实例方法

    8、lambda表达式引用类的实例方法

    9、lambda表达式引用构造器

    10、初识函数式接口

    11、函数式接口作为方法形参

    12、函数式接口作为方法的返回值

    13、常用函数式接口之Supplier

    14、Supplier接口练习之获取最大值

    15、常用函数式接口Consumer

    16、Consumer接口练习之按要求打印信息

    17、常用函数式接口之Predicate

    18、常用函数式接口之Function


    1、多线程实现方式体验lambda表达式

    1. public class LambdaDemo01 {
    2. public static void main(String[] args) {
    3. //实现类的方式实现
    4. // MyRunnable myRunnable = new MyRunnable() ;
    5. // Thread t = new Thread(myRunnable) ;
    6. // t.start();
    7. //匿名内部类的方式实现
    8. // new Thread(new Runnable() {
    9. // @Override
    10. // public void run() {
    11. // System.out.println("线程启动了");
    12. // }
    13. // }).start();
    14. //lambda表达式的方式实现
    15. new Thread(() -> System.out.println("线程启动了")).start();
    16. }
    17. }

    2、lambda表达式练习(抽象方法无参无返回值)

    1. public interface Eatable {
    2. void eat() ;
    3. }
    1. public class EatableImpl implements Eatable {
    2. @Override
    3. public void eat() {
    4. System.out.println("每天一苹果,病魔远离我");
    5. }
    6. }
    1. public class LambdaDemo02 {
    2. public static void main(String[] args) {
    3. //在main方法中使用useEatable
    4. Eatable eatable = new EatableImpl() ;
    5. useEatable(eatable);
    6. //匿名内部类
    7. useEatable(new Eatable() {
    8. @Override
    9. public void eat() {
    10. System.out.println("我爱吃苹果");
    11. }
    12. });
    13. //lambda表达式
    14. useEatable(()-> System.out.println("苹果真好吃啊"));
    15. }
    16. public static void useEatable(Eatable eatable){
    17. eatable.eat();
    18. }
    19. }

    3、lambda表达式练习(抽象方法带参无返回值)

    1. public interface Flyable {
    2. void fly(String s) ;
    3. }
    1. public class LambdaDemo03 {
    2. public static void main(String[] args) {
    3. //不定义接口的实现类直接使用匿名内部类和lambda表达式实现
    4. useFly(new Flyable() {
    5. @Override
    6. public void fly(String s) {
    7. System.out.println(s);
    8. System.out.println("java真好");
    9. }
    10. });
    11. //lambda表达式
    12. useFly(s->{
    13. System.out.println(s);
    14. System.out.println("python也不错");
    15. });
    16. }
    17. private static void useFly(Flyable flyable){
    18. flyable.fly("今天的阳光真好!");
    19. }
    20. }

    4、lambda表达式练习(抽象方法带参带返回值)

    1. public interface Addable {
    2. int add(int x, int y) ;
    3. }
    1. public class LambdaDemo04 {
    2. public static void main(String[] args) {
    3. useAddable(new Addable() {
    4. @Override
    5. public int add(int x, int y) {
    6. return x+y;
    7. }
    8. });
    9. useAddable((x,y)->x+y);
    10. }
    11. private static void useAddable(Addable addable){
    12. int sum = addable.add(10,20) ;
    13. System.out.println(sum);
    14. }
    15. }

    5、lambda表达式的中方法引用

    1. public interface Printable {
    2. void printString(String s) ;
    3. }
    1. public class LambdaDemo05 {
    2. public static void main(String[] args) {
    3. usePrintable(new Printable() {
    4. @Override
    5. public void printString(String s) {
    6. System.out.println(s);
    7. }
    8. });
    9. usePrintable(s-> System.out.println(s));//lambda表达式
    10. usePrintable(System.out::println); //方法引用
    11. }
    12. private static void usePrintable(Printable printable){
    13. printable.printString("爱生活,爱编程");
    14. }
    15. }

    6、lambda表达式中的方法引用2

    1. public interface Converter {
    2. int convert(String s) ;
    3. }
    1. public class LambdaDemo06 {
    2. public static void main(String[] args) {
    3. useConverter(s-> Integer.parseInt(s));
    4. useConverter(Integer::parseInt);
    5. }
    6. private static void useConverter(Converter converter){
    7. int result = converter.convert("666") ;
    8. System.out.println(result);
    9. }
    10. }

    7、lambda表达式引用对象实例方法

    1. public interface Printer {
    2. void printUpperCase(String s) ;
    3. }
    1. public class PrintString {
    2. public void printString(String s){
    3. String result = s.toUpperCase() ;
    4. System.out.println(result);
    5. }
    6. }
    1. public class LambdaDemo07 {
    2. public static void main(String[] args) {
    3. usePrinter(new Printer() {
    4. @Override
    5. public void printUpperCase(String s) {
    6. System.out.println(s.toUpperCase());
    7. }
    8. });
    9. usePrinter(s-> System.out.println(s.toUpperCase()));
    10. //引用对象的实例方法,形参全部传递给该方法做参数
    11. PrintString ps = new PrintString() ;
    12. usePrinter(ps::printString);
    13. }
    14. private static void usePrinter(Printer printer){
    15. printer.printUpperCase("hello java");
    16. }
    17. }

    8、lambda表达式引用类的实例方法

    1. public interface MyString {
    2. String myString(String s, int x, int y) ;
    3. }
    1. public class lambdaDemo08 {
    2. public static void main(String[] args) {
    3. useMyString(new MyString() {
    4. @Override
    5. public String myString(String s, int x, int y) {
    6. return s.substring(x,y);
    7. }
    8. });
    9. useMyString((s,x,y)->s.substring(x,y));
    10. //引用类的实例方法
    11. useMyString(String::substring);
    12. }
    13. private static void useMyString(MyString myString){
    14. String result = myString.myString("hello world", 1,3) ;
    15. System.out.println(result);
    16. }
    17. }

    9、lambda表达式引用构造器

    1. public interface StudentBuilder {
    2. Student build(String name, int age) ;
    3. }
    1. public class Student {
    2. private String name ;
    3. private int age ;
    4. public Student() {
    5. }
    6. public Student(String name, int age) {
    7. this.name = name;
    8. this.age = age;
    9. }
    10. public String getName() {
    11. return name;
    12. }
    13. public void setName(String name) {
    14. this.name = name;
    15. }
    16. public int getAge() {
    17. return age;
    18. }
    19. public void setAge(int age) {
    20. this.age = age;
    21. }
    22. @Override
    23. public String toString() {
    24. return "Student{" +
    25. "name='" + name + '\'' +
    26. ", age=" + age +
    27. '}';
    28. }
    29. }
    1. public class LambdaDemo09 {
    2. public static void main(String[] args) {
    3. useStudentBuilder(new StudentBuilder() {
    4. @Override
    5. public Student build(String name, int age) {
    6. Student student = new Student(name,age) ;
    7. return student ;
    8. }
    9. });
    10. useStudentBuilder((s,x)->new Student(s,x));
    11. useStudentBuilder(Student::new); //引用构造方法
    12. }
    13. private static void useStudentBuilder(StudentBuilder sb){
    14. Student s = sb.build("张三", 18) ;
    15. System.out.println(s.getName() + "," + s.getAge());
    16. }
    17. }

    10、初识函数式接口

    1. @FunctionalInterface
    2. //有且只有一个抽象方法的函数式接口
    3. public interface MyInterface {
    4. void show() ;
    5. }
    1. public class LambdaDemo10 {
    2. public static void main(String[] args) {
    3. MyInterface myInterface = new MyInterface() {
    4. @Override
    5. public void show() {
    6. System.out.println("这是一个函数式接口");
    7. }
    8. };
    9. myInterface.show();
    10. MyInterface myInterface1 = ()-> System.out.println("这是函数式接口") ;
    11. myInterface1.show();
    12. }
    13. }

    11、函数式接口作为方法形参

    1. public class LambdaDemo11 {
    2. public static void main(String[] args) {
    3. //匿名内部类
    4. startThread(new Runnable() {
    5. @Override
    6. public void run() {
    7. System.out.println(Thread.currentThread().getName() + "线程启动了");
    8. }
    9. });
    10. //lambda表达式
    11. startThread(()-> System.out.println(Thread.currentThread().getName() + "线程启动了"));
    12. }
    13. private static void startThread(Runnable runnable){
    14. new Thread(runnable).start();
    15. }
    16. }

    12、函数式接口作为方法的返回值

    1. import java.util.ArrayList;
    2. import java.util.Collections;
    3. import java.util.Comparator;
    4. public class LambdaDemo12 {
    5. public static void main(String[] args) {
    6. ArrayList arrayList = new ArrayList<>() ;
    7. arrayList.add("ccccc");
    8. arrayList.add("aa");
    9. arrayList.add("b");
    10. arrayList.add("ddd");
    11. System.out.println("排序前:" + arrayList);
    12. Collections.sort(arrayList,getComparators()) ;
    13. System.out.println("排序后:" + arrayList);
    14. }
    15. private static Comparator getComparators() {
    16. // return new Comparator() {
    17. // @Override
    18. // public int compare(String o1, String o2) {
    19. // return o1.length() - o2.length();
    20. // }
    21. // };
    22. return ((o1, o2) -> o1.length()-o2.length()) ;
    23. }
    24. }

    13、常用函数式接口之Supplier

    1. import java.util.function.Supplier;
    2. public class LambdaDemo13 {
    3. public static void main(String[] args) {
    4. String s = getString(()->"林青霞") ;
    5. System.out.println(s);
    6. int result = getInteger(()->8) ;
    7. System.out.println(result);
    8. }
    9. private static String getString(Supplier supplier){
    10. return supplier.get() ;
    11. }
    12. private static Integer getInteger(Supplier supplier){
    13. return supplier.get() ;
    14. }
    15. }

    14、Supplier接口练习之获取最大值

    1. import java.util.function.Supplier;
    2. public class LambdaDemo14 {
    3. public static void main(String[] args) {
    4. int [] arr = {1,2,5,4,3} ;
    5. int maxValue = getMax(()->{
    6. int max = arr[0] ;
    7. for(int i=1; i
    8. if(max
    9. max = arr[i] ;
    10. }
    11. }
    12. return max ;
    13. }) ;
    14. System.out.println(maxValue);
    15. }
    16. private static int getMax(Supplier supplier){
    17. return supplier.get() ;
    18. }
    19. }

    15、常用函数式接口Consumer

    1. import java.util.function.Consumer;
    2. public class LambdaDemo15 {
    3. public static void main(String[] args) {
    4. operateString("林青霞",s-> System.out.println(new StringBuilder(s).reverse().toString()));
    5. operateString("林青霞",s-> System.out.println(s),s-> System.out.println(new StringBuilder(s).reverse().toString()));
    6. }
    7. //定义一个方法,消费一个字符串
    8. private static void operateString(String name, Consumer con){
    9. con.accept(name);
    10. }
    11. //定义一个方法,消费字符串两次
    12. private static void operateString(String name, Consumer con1, Consumer con2){
    13. con1.andThen(con2).accept(name);
    14. }
    15. }

    16、Consumer接口练习之按要求打印信息

    1. import java.util.function.Consumer;
    2. public class LambdaDemo16 {
    3. public static void main(String[] args) {
    4. String [] arr = {"张三,18","李四,17","王五,19"} ;
    5. printInfo(arr, str-> System.out.println("姓名:"+str.split(",")[0]),
    6. str -> System.out.println("年龄:" + str.split(",")[1]));
    7. }
    8. private static void printInfo(String []arr, Consumer con1, Consumer con2){
    9. for(String s : arr){
    10. con1.andThen(con2).accept(s);
    11. }
    12. }
    13. }

    17、常用函数式接口之Predicate

    1. import java.util.function.Predicate;
    2. public class LambdaDemo17 {
    3. public static void main(String[] args) {
    4. boolean result1 = checkString("hello",s->s.length()>=8) ;
    5. System.out.println(result1);
    6. boolean result2 = checkString1("hello",s->s.length()>=8) ;
    7. System.out.println(result2);
    8. boolean result3 = checkString2("hello",s->s.length()>=1, s->s.length()<=3) ;
    9. System.out.println(result3);
    10. boolean result4 = checkString3("hello", s->s.length()>=1, s->s.length()<=3) ;
    11. System.out.println(result4);
    12. }
    13. public static boolean checkString(String s, Predicate predicate){
    14. return predicate.negate().test(s) ;
    15. }
    16. public static boolean checkString1(String s, Predicate predicate){
    17. return predicate.test(s) ;
    18. }
    19. public static boolean checkString2(String s, Predicate p1, Predicate p2){
    20. return p1.and(p2).test(s) ;
    21. }
    22. public static boolean checkString3(String s, Predicate p1, Predicate p2){
    23. return p1.or(p2).test(s);
    24. }
    25. }

    18、常用函数式接口之Function

    1. import java.util.function.Function;
    2. public class LambdaDemo18 {
    3. public static void main(String[] args) {
    4. convert("888",s->Integer.parseInt(s));
    5. convert("888",Integer::parseInt);
    6. convert("333",Integer::parseInt,s->String.valueOf(s+333));
    7. }
    8. //把字符串转换成Integer类型
    9. private static void convert(String s, Functionfun){
    10. Integer result = fun.apply(s) ;
    11. System.out.println(result);
    12. }
    13. //定义一个字符串,转换成整型,加上一个整数后转换为字符串
    14. private static void convert(String s, Function fun1, Function fun2){
    15. // Integer result1 = fun1.apply(s) ;
    16. // String result2 = fun2.apply(result1) ;
    17. // System.out.println(result2);
    18. System.out.println(fun1.andThen(fun2).apply(s));
    19. }
    20. }
  • 相关阅读:
    一本通OJ 1376
    m基于matlab的wcdma软切换算法的研究分析和仿真
    使用持久卷部署 WordPress 和 MySQL
    wayland(xdg_wm_base) + egl + opengles 渲染旋转的 3D 立方体实例(十一)
    在Java中线程和进程的区别
    英语写作中“而不是”instead of、other than、rather than的用法(兼“选择”的表达)
    运算符重载
    re:Invent现场直击:无处不在的云计算
    UDP协议
    电脑删除的文件如何找回?
  • 原文地址:https://blog.csdn.net/nuist_NJUPT/article/details/126206311