1. 程式人生 > >java8中幾個函式式介面的小例子

java8中幾個函式式介面的小例子

// 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