Lambda表达式2

2019-03-31  本文已影响0人  ssttIsme

Java Api中也有功能性接口

package lambdaDemo3;

import java.io.File;

public class TestLambda3 {
    public static void main(String[] args) {
        //Java API中的功能性接口
        Runnable r=()->System.out.println("run()");
        Thread t=new Thread(r);
        t.start();
        
        new Thread(()->System.out.println("run() ...")).start();;
        
        File dir=new File("c:/Windows");
        File[] files=dir.listFiles(file->file.getName().endsWith(".ini"));
        for (File f : files) {
            System.out.println(f);
        }
    }

}

运行结果

run()
run() ...
c:\Windows\msdfmap.ini
c:\Windows\psnetwork.ini
c:\Windows\system.ini
c:\Windows\win.ini

package lambdaDemo3;

import java.io.File;

public class TestLambda3 {
    public static void main(String[] args) {
        //Java API中的功能性接口
        Runnable r=()->System.out.println("run()");
        Thread t=new Thread(r);
        t.start();
        
        new Thread(()->System.out.println("run() ...")).start();;
        
        File dir=new File("c:/Windows");
        File[] files=dir.listFiles(file->file.getName().endsWith(".ini"));
        for (File f : files) {
            System.out.println(f);
        }
    }

}

还可对功能性接口加注解@FunctionalInterface
约定接口必须是功能性接口(接口里只能有一个方法)

@FunctionalInterface
interface Truck{
    int test(int a);
}
package lambdaDemo2;

public class TestLambda2 {
    public static void main(String[] args) {
    
        
        //使用Lambda作为参数
        test(a->a+4);

        
    }

    public static void test(Truck truck){
        System.out.println("TestLambda.test(Truck truck)");
        System.out.println(truck.test(6));
    }
}
//功能性接口
@FunctionalInterface
interface Truck{
    int test(int a);
}

运行结果

TestLambda.test(Truck truck)
10

上一篇 下一篇

猜你喜欢

热点阅读