美文网首页
Java8 四大核心函数式接口

Java8 四大核心函数式接口

作者: CodeYang | 来源:发表于2021-10-15 18:38 被阅读0次
/**
 * java8  四大核心函数式接口
 *
 * Consumer<T> : 消费型接口
 *         void accept(T t); 对参数进行处理,没有返回值
 *
 * Supplier<T> : 供给型接口
 *          T get(); 返回对象等数据
 *
 * Function<T,R> : 函数型接口  T 为参数  R为返回值
 *          R apply(T t);对 t 对象处理,返回 R 对象
 *
 * Predicate<T> : 断言型接口(用于一些判断型操作)
 *          boolean test(T t);
 *
 */
public class TestDemo {

    public static void main(String[] args) {

        //Consumer<T> 消费型接口
        testConsumer(10000,(m)-> System.out.println("公司去饭店消费:"+m));

        //Supplier<T> 供给型接口
        List<Integer> integerList = testSupplier(10, () -> (int) (Math.random() * 100));
        System.out.println(integerList);

        //Function<T,R> : 函数型接口  T 为参数  R为返回值
        String newStr = testFunction("\t\t\t 今天星期几", (str) -> str.trim());
        String newStr2 = testFunction("\t\t\t 今天星期几", (str) -> str.substring(4,5));
        System.out.println(newStr);
        System.out.println(newStr2);

        //Predicate<T> : 断言型接口(用于一些判断型操作)
        List<String> strings = testPredicate(Arrays.asList("Hello", "World", "AAAAAA", "AS", "B", "QWEQW"), (str) -> str.length() > 3);
        System.out.println(strings);

    }


    /**
     * Predicate<T> : 断言型接口(用于一些判断型操作)
     * 需求:将满足条件的字符串,放入集合中
     * @param list
     * @param pre
     */
    public static List<String> testPredicate(List<String> list,Predicate<String> pre){
        List<String> strList = new ArrayList<>();
        for (String s : list) {
            if(pre.test(s)){
                strList.add(s);
            }
        }
        return strList;
    }


    /**
     * Function<T,R> : 函数型接口  T 为参数  R为返回值
     * 需求:处理字符串
     * @param str
     * @param fun
     */
    public static String testFunction(String str, Function<String,String> fun){
        return fun.apply(str);
    }

    /**
     * Supplier<T> 供给型接口
     * 需求:产生指定个数的整数,放入集合中去
     * @param num  个数
     * @param sup
     * @return
     */
    public static List<Integer> testSupplier(int num, Supplier<Integer> sup){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(sup.get());
        }
        return list;
    }

    /**
     * Consumer<T> 消费型接口
     * @param money
     * @param con
     */
    public static void testConsumer(double money, Consumer<Double> con){
        con.accept(money);
    }

}

相关文章

网友评论

      本文标题:Java8 四大核心函数式接口

      本文链接:https://www.haomeiwen.com/subject/fbwmoltx.html