Java8新特性之函數式接口學習

函數式接口

只包含一個方法的接口(default方法除外)稱爲函數式接口。可用@FunctionalInterface註解修飾,可以語法檢查。

@FunctionalInterface
public interface InterfaceTest {
	void test();
    
	default void defaultMethod() {}
}

四大內置核心函數式接口

  • Lambda表達式需要用到函數式接口,而大部分的Lambda表達式的函數式接口都是很簡單的,這些簡單的接口如果需要程序員手動再新建的話,實在太麻煩,所以Java8爲我們提供了4類內置函數式接口,方便我們調用, 這4類接口已經可以解決我們開發過程中絕大部分的問題 。
  1. 消費型接口(有去無回)
@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
    ...
}

使用示例:(將字符串作爲輸入,然後做打印處理,相當於“消費”了)

@Test
public void test1() {
	Consumer<String> consumer = (str) -> System.out.println(str);
	consumer.accept("hello consumer!");
}
  1. 供給型接口(憑空捏造)

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

    使用示例:(隨機生成一個100以內的整數,無入參)

    @Test
    public void test2() {
    	Supplier<Integer>  supplier = () -> (int)(Math.random()*100);
    	Integer num = supplier.get();
    	System.out.println(num);
    }
    
    
  2. 函數型接口(有來有回)

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

    使用示例:(傳入一個字符串,返回一個前後無空格的字符串,”有來有回“)

    @Test
    public void test3() {
    	Function<String, String> function = (str) -> str.trim();		
        String str = function.apply("\t\t\tHello! ");
    	System.out.println(str);
    }
    
  3. 斷言型接口(判斷對錯)

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

    使用示例:

    @Test
    public void test4() {
    	List<Integer> list = Arrays.asList(1, 3, 5, 10, 22);
    	//過濾得到所有奇數
    	List<Integer> list1 = filterNum(list, (num) -> num % 2 == 0 ? false : true);
    	list1.forEach(System.out::println);
    		
    	System.out.println("========================");
    		
    	//過濾得到所有大於5的數
    	List<Integer> list2 = filterNum(list, (num) -> num > 5);
    	list2.forEach(System.out::println);
    }
    	
    public List<Integer> filterNum(List<Integer> list, Predicate<Integer> predicate){
    	List<Integer> res = new ArrayList<>();
    	for (Integer num : list) {
    		if (predicate.test(num)) {
    			res.add(num);
    		}
    	}
    	return res;
    }
    

除上述四個函數式接口外,Java8還提供了一些衍生的接口幫助我們處理更多的情況

public interface BiConsumer<T, U> {void accept(T t, U u);} 
public interface BiFunction<T, U, R> {R apply(T t, U u);}
public interface BiPredicate<T, U> {boolean test(T t, U u);}

public interface DoubleConsumer {void accept(double value);}
public interface DoubleSupplier {double getAsDouble();}
public interface DoubleFunction<R> {R apply(double value);}
public interface DoublePredicate {boolean test(double value);...}

...

在這裏插入圖片描述
所以我們可以根據不同的場景選擇使用不同的接口,當然也可以自定義。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章