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。对象