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

Posted nuist__NJUPT

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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表达式

public class LambdaDemo01 
    public static void main(String[] args) 
        //实现类的方式实现
//        MyRunnable myRunnable = new MyRunnable() ;
//        Thread t = new Thread(myRunnable) ;
//        t.start();

        //匿名内部类的方式实现
//        new Thread(new Runnable() 
//            @Override
//            public void run() 
//                System.out.println("线程启动了");
//            
//        ).start();

        //lambda表达式的方式实现
        new Thread(() -> System.out.println("线程启动了")).start();
    

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

public interface Eatable 
    void eat() ;


public class EatableImpl implements Eatable 
    @Override
    public void eat() 
        System.out.println("每天一苹果,病魔远离我");
    

public class LambdaDemo02 
    public static void main(String[] args) 
        //在main方法中使用useEatable
        Eatable eatable = new EatableImpl() ;
        useEatable(eatable);

        //匿名内部类
        useEatable(new Eatable() 
            @Override
            public void eat() 
                System.out.println("我爱吃苹果");
            
        );

        //lambda表达式
        useEatable(()-> System.out.println("苹果真好吃啊"));


    
    public static void useEatable(Eatable eatable)
        eatable.eat();
    

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

public interface Flyable 
    void fly(String s) ;

public class LambdaDemo03 
    public static void main(String[] args) 
        //不定义接口的实现类直接使用匿名内部类和lambda表达式实现
        useFly(new Flyable() 
            @Override
            public void fly(String s) 
                System.out.println(s);
                System.out.println("java真好");
            
        );

        //lambda表达式
        useFly(s->
            System.out.println(s);
            System.out.println("python也不错");
        );
    
    private static void useFly(Flyable flyable)
        flyable.fly("今天的阳光真好!");
    

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

public interface Addable 
    int add(int x, int y) ;

public class LambdaDemo04 
    public static void main(String[] args) 
        useAddable(new Addable() 
            @Override
            public int add(int x, int y) 
                return x+y;
            
        );

        useAddable((x,y)->x+y);
    
    private static void useAddable(Addable addable)
        int sum = addable.add(10,20) ;
        System.out.println(sum);
    

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


public interface Printable 
    void printString(String s) ;

public class LambdaDemo05 
    public static void main(String[] args) 
        usePrintable(new Printable() 
            @Override
            public void printString(String s) 
                System.out.println(s);
            
        );
        usePrintable(s-> System.out.println(s));//lambda表达式
        usePrintable(System.out::println); //方法引用
    
    private static void usePrintable(Printable printable)
        printable.printString("爱生活,爱编程");
    

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

public interface Converter 
    int convert(String s) ;

public class LambdaDemo06 
    public static void main(String[] args) 
        useConverter(s-> Integer.parseInt(s));
        useConverter(Integer::parseInt);
    
    private static void useConverter(Converter converter)
        int result = converter.convert("666") ;
        System.out.println(result);
    

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


public interface Printer 
    void printUpperCase(String s) ;

public class PrintString 
    public void printString(String s)
        String result = s.toUpperCase() ;
        System.out.println(result);
    

public class LambdaDemo07 
    public static void main(String[] args) 
        usePrinter(new Printer() 
            @Override
            public void printUpperCase(String s) 
                System.out.println(s.toUpperCase());
            
        );

        usePrinter(s-> System.out.println(s.toUpperCase()));

        //引用对象的实例方法,形参全部传递给该方法做参数
        PrintString ps = new PrintString() ;
        usePrinter(ps::printString);
    
    private static void usePrinter(Printer printer)
        printer.printUpperCase("hello java");
    

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

public interface MyString 
    String myString(String s, int x, int y) ;

public class lambdaDemo08 
    public static void main(String[] args) 
        useMyString(new MyString() 
            @Override
            public String myString(String s, int x, int y) 
                return s.substring(x,y);
            
        );
        useMyString((s,x,y)->s.substring(x,y));

        //引用类的实例方法
        useMyString(String::substring);

    
    private static void useMyString(MyString myString)
        String result = myString.myString("hello world", 1,3) ;
        System.out.println(result);
    

9、lambda表达式引用构造器

public interface StudentBuilder 
    Student build(String name, int age) ;

public class Student 
    private  String name ;
    private int age ;

    public Student() 
    

    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 +
                '';
    


public class LambdaDemo09 
    public static void main(String[] args) 
        useStudentBuilder(new StudentBuilder() 
            @Override
            public Student build(String name, int age) 
                Student student = new Student(name,age) ;
                return student ;
            
        );

        useStudentBuilder((s,x)->new Student(s,x));

        useStudentBuilder(Student::new); //引用构造方法


    
    private static void useStudentBuilder(StudentBuilder sb)
        Student s = sb.build("张三", 18) ;
        System.out.println(s.getName() + "," + s.getAge());
    

10、初识函数式接口


@FunctionalInterface
//有且只有一个抽象方法的函数式接口
public interface MyInterface 
    void show() ;

public class LambdaDemo10 
    public static void main(String[] args) 
        MyInterface myInterface = new MyInterface() 
            @Override
            public void show() 
                System.out.println("这是一个函数式接口");
            
        ;
        myInterface.show();

        MyInterface myInterface1 = ()-> System.out.println("这是函数式接口") ;
        myInterface1.show();
    

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

public class LambdaDemo11 
    public static void main(String[] args) 
        //匿名内部类
        startThread(new Runnable() 
            @Override
            public void run() 
                System.out.println(Thread.currentThread().getName() + "线程启动了");
            
        );
        //lambda表达式
        startThread(()-> System.out.println(Thread.currentThread().getName() + "线程启动了"));

    
    private static void startThread(Runnable runnable)
        new Thread(runnable).start();
    

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class LambdaDemo12 
    public static void main(String[] args) 
        ArrayList<String> arrayList = new ArrayList<>() ;

        arrayList.add("ccccc");
        arrayList.add("aa");
        arrayList.add("b");
        arrayList.add("ddd");

        System.out.println("排序前:" + arrayList);
        Collections.sort(arrayList,getComparators()) ;
        System.out.println("排序后:" + arrayList);
    

    private static Comparator<String> getComparators() 
//        return new Comparator<String>() 
//            @Override
//            public int compare(String o1, String o2) 
//                return o1.length() - o2.length();
//            
//        ;
        
        return ((o1, o2) -> o1.length()-o2.length()) ;
    

13、常用函数式接口之Supplier

import java.util.function.Supplier;

public class LambdaDemo13 
    public static void main(String[] args) 
        String s = getString(()->"林青霞") ;
        System.out.println(s);
        int result = getInteger(()->8) ;
        System.out.println(result);
    
    private static String getString(Supplier<String> supplier)
       return  supplier.get() ;
    
    private static Integer getInteger(Supplier<Integer> supplier)
        return supplier.get() ;
    

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

import java.util.function.Supplier;

public class LambdaDemo14 
    public static void main(String[] args) 
        int [] arr = 1,2,5,4,3 ;
        int maxValue = getMax(()->
            int max = arr[0] ;
            for(int i=1; i<arr.length; i++)
                if(max<arr[i])
                    max = arr[i] ;
                
            
            return max ;
        ) ;
        System.out.println(maxValue);
    
    private static int getMax(Supplier<Integer> supplier)
        return supplier.get() ;
    

15、常用函数式接口Consumer


import java.util.function.Consumer;

public class LambdaDemo15 
    public static void main(String[] args) 
        operateString("林青霞",s-> System.out.println(new StringBuilder(s).reverse().toString()));
        operateString("林青霞",s-> System.out.println(s),s-> System.out.println(new StringBuilder(s).reverse().toString()));
    
    //定义一个方法,消费一个字符串
    private static void operateString(String name, Consumer<String> con)
        con.accept(name);
    
    //定义一个方法,消费字符串两次
    private static void operateString(String name, Consumer<String> con1, Consumer<String> con2)
        con1.andThen(con2).accept(name);
    

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

import java.util.function.Consumer;

public class LambdaDemo16 
    public static void main(String[] args) 
        String [] arr = "张三,18","李四,17","王五,19" ;
        printInfo(arr, str-> System.out.println("姓名:"+str.split(",")[0]),
                str -> System.out.println("年龄:" + str.split(",")[1]));

    
    private static void printInfo(String []arr, Consumer<String> con1, Consumer<String> con2)
        for(String s : arr)
            con1.andThen(con2).accept(s);
        
    

17、常用函数式接口之Predicate

import java.util.function.Predicate;

public class LambdaDemo17 
    public static void main(String[] args) 
        boolean result1 = checkString("hello",s->s.length()>=8) ;
        System.out.println(result1);

        boolean result2 = checkString1("hello",s->s.length()>=8) ;
        System.out.println(result2);

        boolean result3 = checkString2("hello",s->s.length()>=1, s->s.length()<=3) ;
        System.out.println(result3);

        boolean result4 = checkString3("hello", s->s.length()>=1, s->s.length()<=3) ;
        System.out.println(result4);


    
    public static boolean checkString(String s, Predicate<String> predicate)
        return predicate.negate().test(s) ;
    
    public static boolean checkString1(String s, Predicate<String> predicate)
        return predicate.test(s) ;
    
    public static boolean checkString2(String s, Predicate<String> p1, Predicate<String> p2)
        return p1.and(p2).test(s) ;
    
    public static boolean checkString3(String s, Predicate<String> p1, Predicate<String> p2)
        return p1.or(p2).test(s);
    

18、常用函数式接口之Function

import java.util.function.Function;

public class LambdaDemo18 
    public static void main(String[] args) 
        convert("888",s->Integer.parseInt(s));
        convert("888",Integer::parseInt);
        convert("333",Integer::parseInt,s->String.valueOf(s+333));
    
    //把字符串转换成Integer类型
    private static void convert(String s, Function<String, Integer>fun)
        Integer result = fun.apply(s) ;
        System.out.println(result);
    
    //定义一个字符串,转换成整型,加上一个整数后转换为字符串
    private static void convert(String s, Function<String,Integer> fun1, Function<Integer,String> fun2)
//        Integer result1 = fun1.apply(s) ;
//        String result2 = fun2.apply(result1) ;
//        System.out.println(result2);

        System.out.println(fun1.andThen(fun2).apply(s));

    

以上是关于Java之lambda表达式与函数式接口的主要内容,如果未能解决你的问题,请参考以下文章

Java8新特性——Lambda表达式之基本语法 & 自定义函数式接口

java8新特性之Lambda表达式入门

Java8新特性——Lambda表达式之四大核心函数式接口 & 方法/构造器/数组引用

Java8新特性——Lambda表达式之四大核心函数式接口 & 方法/构造器/数组引用

Java8 Lambda原理

Java新特性之函数式接口