1. 程式人生 > >JDK8新特性01 Lambda表示式02

JDK8新特性01 Lambda表示式02

//函式式介面:只有一個抽象方法的介面稱為函式式介面。 可以使用註解 @FunctionalInterface 修飾
@FunctionalInterface
public interface MyFun {
	public Integer getValue(Integer num);
}
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import org.junit.Test;

/*
 * 一、Lambda 表示式的基礎語法:Java8中引入了一個新的操作符 "->" 該操作符稱為箭頭操作符或 Lambda 操作符
 * 						    箭頭操作符將 Lambda 表示式拆分成兩部分:
 * 
 * 左側:Lambda 表示式的引數列表
 * 右側:Lambda 表示式中所需執行的功能, 即 Lambda 體
 * 
 * 語法格式一:無引數,無返回值
 * 		() -> System.out.println("Hello Lambda!");
 * 
 * 語法格式二:有一個引數,並且無返回值
 * 		(x) -> System.out.println(x)
 * 
 * 語法格式三:若只有一個引數,小括號可以省略不寫
 * 		x -> System.out.println(x)
 * 
 * 語法格式四:有兩個以上的引數,有返回值,並且 Lambda 體中有多條語句
 *		Comparator<Integer> com = (x, y) -> {
 *			System.out.println("函式式介面");
 *			return Integer.compare(x, y);
 *		};
 *
 * 語法格式五:若 Lambda 體中只有一條語句, return 和 大括號都可以省略不寫
 * 		Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
 * 
 * 語法格式六:Lambda 表示式的引數列表的資料型別可以省略不寫,因為JVM編譯器通過上下文推斷出,資料型別,即“型別推斷”
 * 		(Integer x, Integer y) -> Integer.compare(x, y);
 * 
 * 上聯:左右遇一括號省
 * 下聯:左側推斷型別省
 * 橫批:能省則省
 * 
 * 二、Lambda 表示式需要“函式式介面”的支援
 * 函式式介面:介面中只有一個抽象方法的介面,稱為函式式介面。 可以使用註解 @FunctionalInterface 修飾
 * 			 可以檢查是否是函式式介面
 */
public class TestLambda2 {
	
	@Test
	public void test1(){
		int num = 0;//jdk 1.7 前,必須是 final
		
		Runnable r = new Runnable() {
			@Override
			public void run() {
				System.out.println("Hello World!" + num);
			}
		};
		
		r.run();
		
		System.out.println("-------------------------------");
		
		Runnable r1 = () -> System.out.println("Hello Lambda!");
		r1.run();
	}
	
	@Test
	public void test2(){
		Consumer<String> con = x -> System.out.println(x);
		con.accept("我大尚矽谷威武!");
	}
	
	@Test
	public void test3(){
		Comparator<Integer> com = (x, y) -> {
			System.out.println("函式式介面");
			return Integer.compare(x, y);
		};
	}
	
	@Test
	public void test4(){
		Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
	}
	
	@Test
	public void test5(){
//		String[] strs;
//		strs = {"aaa", "bbb", "ccc"};
		
		List<String> list = new ArrayList<>();
		
		show(new HashMap<>());
	}

	public void show(Map<String, Integer> map){
		
	}
	
	//需求:對一個數進行運算
	@Test
	public void test6(){
		Integer num = operation(100, (x) -> x * x);
		System.out.println(num);
		
		System.out.println(operation(200, (y) -> y + 200));
	}
	
	public Integer operation(Integer num, MyFun mf){
		return mf.getValue(num);
	}
}