java8 - 內置函數式接口(Supplier、Function)

Supplier

若是須要建立類型T的對象,就可使用這個Supplier接口。app

建立一個字符串並輸出
public class SupplierDemo {
    public static void main(String[] args) {
        System.out.println(getStr(() -> "hello wolrd"));
    }

    public static <T> T getStr(Supplier<T> supplier) {
        return supplier.get();
    }
}

Function

接受一個泛型T的對象,並返回一個泛型R的對象code

經過字符串,返回對應的長度
public class FunctionDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("1", "2", "3", "11", "22", "33");
        getLength(list, t -> t.length());
    }

    public static <T, R> void getLength(List<T> list, Function<T, R> function) {
        Map<T, R> map = new HashMap<>();
        for (T t : list) {
            map.put(t, function.apply(t));
        }
        System.out.println(map);
    }
}

這邊傳入的類型是String,返回的int。對象

相關文章
相關標籤/搜索