编程知识 cdmana.com

java8:四大函数式接口(Consumer、Supplier、Function、Predicate)

1、 消费型接口:Consumer

(1)函数式接口

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

测试类

   public void happy(String string, Consumer<String> con) {
        con.accept(string);
    }

    @Test
    public void test1() {
        happy("zhai", (m) -> System.out.println("你好" + m ));
    }
你好zhai

消费型接口特点:有输入但是无返回值

 

2、供给型接口:Supplier

(1)函数式接口

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

(2)测试

 public List<Integer> getNumList(int num, Supplier<Integer> sup) {
        List<Integer> list = new ArrayList<>();

        for (int i = 0; i < num; i++) {
            Integer n = sup.get();
            list.add(n);
        }

        return list;
    }

    @Test
    public void test2() {
        List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));

        for (Integer num : numList) {
            System.out.println(num);
        }
    }
75
1
61
85
97
25
94
41
24
90

无输入参数,有输出

 

3、函数型接口:Function

(1)函数式接口

@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

(2)测试

@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
你好
llo

有输入参数,有返回值

 

4、断言型接口:Predicate

(1)函数式接口

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

(2)测试

   public List<String> filterStr(List<String> list, Predicate<String> pre) {
        List<String> strList = new ArrayList<>();

        for (String str : list) {
            if (pre.test(str)) {
                strList.add(str);
            }
        }

        return strList;
    }

    @Test
    public void test4() {
        List<String> list = Arrays.asList("Hello", "nihaoyyyy", "Lambda", "www", "ok");
        List<String> strList = filterStr(list, (s) -> s.length() > 3);

        for (String str : strList) {
            System.out.println(str);
        }
    }

有输入,返回值是Boolean类型的

 

5、其他接口

(1)其他接口

 

版权声明
本文为[怀梦想,致远方]所创,转载请带上原文链接,感谢
https://www.cnblogs.com/zhai1997/p/13958525.html

Scroll to Top