java8 -- 內置的四大核心函數式接口

Consumer<T> : 消費型接口
    void accept(T t);

 Supplier<T> : 提供型接口
     T get(); 
 
 Function<T, R> : 函數型接口
     R apply(T t);

Predicate<T> : 斷言型接口
    boolean test(T t);
/**
 * Consumer<T> : 消費型接口
 *      void accept(T t);
 * Supplier<T> : 提供型接口
 *      T get();
 * Function<T, R> : 函數型接口
 *      R apply(T t);
 * Predicate<T> : 斷言型接口
 *      boolean test(T t);
 */
public class MyFunction {
    // Consumer<T> 消費型接口
    @Test
    public void test1() {
        happy(10000, m -> System.out.println("消費 " + m + " 元"));
    }

    public void happy(double money, Consumer<Double> con) {
        con.accept(money);
    }

    // Supplier<T> 供給型接口
    // 產生指定個數的整數並放入集合中
    @Test
    public void test2() {
        System.out.println(createIntegerList(10, () -> (int)(Math.random() * 100)));
    }

    public List<Integer> createIntegerList(int num, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(supplier.get());
        }

        return list;
    }

    // Function<T, R> 函數型接口
    // 需求,用來處理字符串
    @Test
    public void test3 () {
        String str = "abcdefght";
        System.out.println(strHandler(str, e -> str.substring(2, 4)));
    }

    public String strHandler(String str, Function<String, String> function) {
        return function.apply(str);
    }

    // Predicate<T> 斷言型接口
    // 需求:將滿足條件的字符串添加到集合中
    @Test
    public void test4() {
        List<String> strings = Arrays.asList("aaaa", "bbbb", "cccccc", "dddd");
        System.out.println(filterStr(strings, e -> e.length() <= 4));
    }

    public List<String> filterStr(List<String> list, Predicate<String> predicate) {
        List<String> result = new ArrayList<>();
        for (String str : list) {
            if (predicate.test(str)) {
                result.add(str);
            }
        }

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