1. 程式人生 > >JAVA8學習筆記(二)----三個預定義接口

JAVA8學習筆記(二)----三個預定義接口

筆記 mps pub cti set nal () ack temp

三個函數接口概述

JDK預定義了很多函數接口以避免用戶重復定義。最典型的是Function

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

這個接口代表一個函數,接受一個T類型的參數,並返回一個R類型的返回值。

另一個預定義函數接口叫做Consumer,跟Function的唯一不同是它沒有返回值。

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

還有一個Predicate,用來判斷某項條件是否滿足。經常用來進行篩濾操作:

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

綜上所述,一個λ表達式其實就是定義了一個匿名方法,只不過這個方法必須符合至少一個函數接口。

基本應用

POJO
public class Emp {
    private int empno;
    private String ename;
    //getter|setter|toString略
    public static void printEmp(Emp emp){
        System.out.println(
"empno:"+emp.getEmpno()+"\nename:"+emp.getEname()); } }
靜態List
static List<Emp> emps = Arrays.asList(
        new Emp(1, "yw"),
        new Emp(2, "yt"),
        new Emp(3, "yp"),
        new Emp(4, "yc"));
Predicate應用
@Test
public void testPredicate()
{
    Predicate<Emp> predicate = emp -> emp.getEmpno()>1;
    
for(Emp e:emps) { if(predicate.test(e)) { Emp.printEmp(e); } } }
運行

技術分享

Function應用
@Test
public void testFunction() {
    //抽取員工的名稱
    Function<Emp,String> function = emp -> emp.getEname();

    for (Emp emp : emps)
    {
        String ename = function.apply(emp);
        System.out.println(ename);
    }
}
運行

技術分享

Consumer應用
@Test
public void testConsumer()
{
    Consumer<Emp> consumer = Emp::printEmp;
    for(Emp e:emps)
    {
        consumer.accept(e);
    }
}
運行

技術分享

綜合應用

預處理函數
private <T,R> void printEmpNameWhenEmpNoLg1(Iterable<T> source,Predicate<T> predicate,Function<T,R> function,
                                            Consumer<R> consumer)
{
    for(T t:source)
    {
        if(predicate.test(t))
        {
            R r = function.apply(t);
            consumer.accept(r);
        }
    }
}

此函數包含四個參數,分別為實現了Iterable接口的List(此例中即emps)及三個預定義函數接口。應用如下:

@Test
public void testFunctionInterface()
{
    Predicate<Emp> predicate = emp -> emp.getEmpno()>1;
    Function<Emp,String> function = emp -> emp.getEname();
    Consumer<String> consumer = System.out::println;
    printEmpNameWhenEmpNoLg1(emps,predicate,function,consumer);
}
運行

技術分享

JAVA8學習筆記(二)----三個預定義接口