文章出處
文章列表
// Function<T, R> -T作為輸入,返回的R作為輸出 Function<String,String> function = (x) -> {System.out.print(x+": ");return "Function";}; System.out.println(function.apply("hello world")); //Predicate<T> -T作為輸入,返回的boolean值作為輸出 Predicate<String> pre = (x) ->{System.out.print(x);return false;}; System.out.println(": "+pre.test("hello World")); //Consumer<T> - T作為輸入,執行某種動作但沒有返回值 Consumer<String> con = (x) -> {System.out.println(x);}; con.accept("hello world"); //Supplier<T> - 沒有任何輸入,返回T Supplier<String> supp = () -> {return "Supplier";}; System.out.println(supp.get()); //BinaryOperator<T> -兩個T作為輸入,返回一個T作為輸出,對于“reduce”操作很有用 BinaryOperator<String> bina = (x,y) ->{System.out.print(x+" "+y);return "BinaryOperator";}; System.out.println(" "+bina.apply("hello ","world"));
輸出如下:
hello world: Function hello World: false hello world Supplier hello world BinaryOperator
import java.time.Instant; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; public class Test { public static void main(String ... args) throws Exception{ //1:lambda表達式和功能接口 Add a = (x, y) -> x+y; System.out.println(a.add(100,200)); System.out.println("------------------------------------------1"); //2:lambda表達式和集合 List<String> list = Arrays.asList("aaa","bbbb","cccc"); list.forEach(e -> {System.out.println(e);}); System.out.println("------------------------------------------2"); //3:接口中可以包含靜態方法 Add.interfaceStaticMethod(); System.out.println("------------------------------------------3"); //4:接口中可以包含默認方法,默認方法實現類并不是必須實現。 Add add = (x,y) -> x-y; add.defaultMethod(); System.out.println("------------------------------------------4"); //5:java.util.function 包下提供的函數式接口 String s = "hello"; Function<String,String> function = x -> x+" world"; System.out.println(function.apply(s)); System.out.println("------------------------------------------5"); //6:java.util.stream包 List<Integer> strings = Arrays.asList(1,2,3); IntStream stream = strings.stream().mapToInt(Integer::valueOf); stream.forEach(x->{System.out.println(x);}); System.out.println("------------------------------------------6"); System.out.println(Instant.now().getNano()); System.out.println(Instant.MIN); System.out.println(Instant.MAX); } } @FunctionalInterface //函數式接口(也叫功能接口),此接口中只能有一個抽象方法。函數式接口可以用lambda表達式實例化。 interface Add { public int add(int x,int y); public static void interfaceStaticMethod(){ System.out.println("interface static method"); } public default void defaultMethod(){ System.out.println("default method"); } }
輸出如下:
300 ------------------------------------------1 aaa bbbb cccc ------------------------------------------2 interface static method ------------------------------------------3 default method ------------------------------------------4 hello world ------------------------------------------5 1 2 3 ------------------------------------------6 280000000 -1000000000-01-01T00:00:00Z +1000000000-12-31T23:59:59.999999999Z
文章列表
全站熱搜
留言列表