java 8内置的四大核心函数式接口

Consumer<T> : 消费性接口

返回值  void accept(T t);

public void happy(double money, Consumer<Double> con) {
        con.accept(money);
    }
    @Test
    public void test1() {
        happy(1999.99, m -> System.out.println("吃饭花了" + m + "元"));
    }

Supplier<T> :供给型接口

返回值   T get();

//产生特定个数整数,放在集合中
    public List<Integer> getList(int num, Supplier<Integer> sp) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Integer n = sp.get();
            list.add(n);
        }
        return list;
    }

    @Test
    public void test2() {
        List<Integer> list = getList(13, () -> (int) (Math.random() * 100));
        for (Integer num : list
        ) {
            System.out.println(num);
        }
    }

Function<T,R>函数式接口

返回值    R apply<T t>

public String strHandler(String str, Function<String, String> fun) {
        return fun.apply(str);
    }
    @Test
    public void test3() {
        String s = strHandler("\t\t\t 人呢   ", t -> t.trim());
        System.out.println(s);

        String s2 = strHandler(" 人呢123456   ", t -> t.trim().substring(2, 4));
        System.out.println(s2);
    }

Predicate<T> 断言型接口

返回值  boolean test(T t);

//需求将满足条件的字符串放进集合
    public List<String> strList(List<String> list, Predicate<String> pre) {
        List<String> list1 = new ArrayList<>();
        for (String li : list
        ) {
            if (pre.test(li)) {
                list1.add(li);
            }
        }
        return list1;
    }
    @Test
    public void test4() {
        List<String> list = Arrays.asList("123", "11", "小明上学", "ok");
        List<String> stringList = strList(list, pr -> pr.length() > 2);
        for (String s : stringList
        ) {
            System.out.println(s);
        }
    }
posted @ 2020-04-23 21:55  程程111  阅读(195)  评论(0编辑  收藏  举报