Java8 新特性(一)- Lambda 表達式


2014年3月18日發布了JavaSE 8

不追求技術的新,追求技術的穩定

本質:Lambda 表達式是一個匿名函數
作用:簡化代碼,增強代碼的表達力

Lambda 語法格式

// 格式1:無參無返回值
() -> System.out.println("Hello World!");

// 格式2:有參無返回值
(x) -> System.out.println(x);

// 格式3:有參有返回值
(x) -> x * x;

// 格式4:多參有返回值
(x, y) -> x + y;

// 格式5:函數體包含多條語句
(x, y) -> {
    System.out.println("加法運算");
    return x + y;
}

Lambda 表達式中的參數的數據類型可以省略,JVM 編譯器能夠根據上下文推算出,即“類型推斷”

兩個例子

/** 1. Comparator **/
TreeSet<Integer> ts1 = new TreeSet<>(new Comparator<Integer>(){
    @Override
    public int compare(Integer i1, Integer i2) {
        return Integer.compare(i1, i2);
    }
});
// lambda 表達式
TreeSet<Integer> ts2 = new TreeSet<>((i1, i2) -> {
    return Integer.compare(i1, i2);
});
// 等同於(使用方法引用還可以再次簡化)
TreeSet<Integer> ts3 = new TreeSet<>((i1, i2) -> Integer.compare(i1, i2));


/** 2. Runnable */
Thread t1 = new Thread(new Runnable(){
    @Override
    public void run() {
        System.out.println("當前線程:" + Thread.currentThread().getName());
    }
});
// lambda 表達式
Thread t2 = new Thread(() -> {
    System.out.println("當前線程:" + Thread.currentThread().getName());
});

函數式接口

!!Lambda 表達式需要函數式接口的支持

函數式接口:接口只有一個抽象方法

可以使用注解 @FunctionalInterface 修飾接口,檢查是否是函數式接口

// 定義函數式接口
@FunctionalInterface
public interface Calculator<T> {
    public T calculate(T x, T y);
}

// 使用函數式接口
Calculator<Integer> calculatorAdd = (x, y) -> x + y;
Integer result = calculatorAdd.calculate(3, 5);

Java 內置了四大核心函數式接口:

消費型接口 Consumer<T>:消費一個參數對象

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
    ...
}

供給型接口 Supplier<T>:返回一個對象

@FunctionalInterface
public interface Supplier<T> {
    T get();
}

函數型接口 Function<T, R>:傳遞一個參數,返回一個值

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
    ...
}

斷定型接口 Predicate<T>:判斷參數是否滿足約束

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
    ...
}

對於Java內置函數式接口建議結合 stream 方法理解,在這里了解即可

除了這4大核心函數式接口外,還有由它們延伸出的一些變種,比如二元消費型接口 BiConsumer<T, U>

public interface BiConsumer<T, U> {
    void accept(T t, U u);
    ...
}

方法引用

將 lambda 體代碼封裝為方法,然后方法引用,再次簡化代碼。

方法引用格式:類名::方法名對象::方法名

溫馨提示:

實際上,在開發工具 IDEA 中,會自動提示使用方法引用簡化代碼,你只需按 ALT+Eenter 快捷鍵,根據提示選擇操作即可

如果你想要深入了解方法引用的使用原則,可以繼續往下看。(即使不看也沒大問題,有開發工具幫你優化)

使用方法引用改寫 Comparator 例子中的 lambda 表達式

// 
TreeSet<Integer> ts3 = new TreeSet<>((i1, i2) -> Integer.compare(i1, i2));
// 使用方法引用
TreeSet<Integer> ts4 = new TreeSet<>(Integer::compare);

(第一種情況)實現函數式接口方法的參數列表,必須和方法引用方法的參數列表保持一致

Comparator.compare(o1, o2) 的 o1, o2 與 Integer.compare(i1, i2) 中的 i1, i2 對應,所以才能夠使用方法應用。

當函數式接口方法只有一個參數時(小例子):

   
   @Test
   public void test3() {
   	List<String> stringList = Arrays.asList("北京", "天津", "上海");
       // `Consumer.accept(t)` 的參數 t 與 `System.out.println(o)` 的 o 對應
   	show(System.out::println, stringList);
   }
   // 自定義一個函數
   void show(Consumer<String> consumer, List<String> list) {
   	for (String s : list) {
   		consumer.accept(s);
   	}
   }

還有第二種情況

TreeSet<Integer> ts3 = new TreeSet<>((i1, i2) -> i1.compareTo(i2));
// 使用方法引用
TreeSet<Integer> ts4 = new TreeSet<>(Integer::compareTo);

Comparator.compare(o1, o2) 的 o1, o2 與 i1.compareTo(i2) 中 i1, i2 對應,這樣也能使用方法引用。

(第二種情況)假設函數式接口方法參數有 (x1, x2),而方法實現是 x1.fun(x2) 這種形式,照樣使用方法引用

如果理解了它們的規律,推而廣之,可以試試抽象方法含有三個參數的情況。

准備工作:找一個三參數的函數式接口

	@Test
	public void test4() {
		String s = "Hello World";
		Integer start = 0;
		Integer length = 5;
		String r1 = consume((o1, o2, o3) -> {
			return o1.substring(o2, o3);
		}, s, start, length);
		System.out.println(r1);

		String r2 = consume(String::substring, s, start, length);
		System.out.println(r2);
	}
	String consume(TripleFunction<String, Integer, Integer, String> tripleFunction, 
                                 String s, 
                                 Integer start, 
                                 Integer length) {
		return tripleFunction.apply(s, start, length);
	}
	// 自定義三參數函數式接口
	@FunctionalInterface
	interface TripleFunction<T, U, E, R> {
		R apply(T t, U u, E e);
	}

這里 函數式接口 TripleFunction 的抽象方法 apply(T t, U u, E e)中的參數 t, u, e 與 s.substring(start, length) 中的 s,start, length 對應

小結:

設函數式接口抽象方法 abstractFun(n1, n2, n3, ..., nn)
**有方法fun(n1, n2, n3, ..., nn)n1.fun(n2, n3, ..., nn) ** 實現了 lambda 體的代碼功能
就可使用方法引用 ClassName::fun

構造器引用

用法:


Function<Integer, MyClass> fun1 = (i) -> new MyClass(i);
// 使用構造器引用
Function<Integer, MyClass> fun2 = MyClass::new;

Function<Integer, Integer[]> fun3 = (n) -> new Integer[n];
// 使用構造器引用
Function<Integer, Integer[]> fun4 = Integer[]::new;

函數式接口方法參數列表,必須和構造函數參數列表一致 (和方法應用的第一種情況相同)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM