常用的函数式接口-Consumer接口练习-字符串拼接输出和Predicate接口

常用的函数式接口-Consumer接口练习-字符串拼接输出

复制代码
/*
        练习:
        字符串数组当中存有多条信息,请按照格式“姓名:Xx。性别: Xx。”的格式将信息打印出来。
        要求将打印姓名的动作作为第一个consumer接口的Lambda实例,
        将打印性别的动作作为第二个consumer接口的Lambda实例,
        将两个consumer接口按照顺序“拼接”到一起。
 */
public class DemoTest {
    //定义一个方法,参数传递String类型的数组和两个consumer接口,泛型使用String
    public static void printInfo(String[] arr, Consumer<String> con1,Consumer<String> con2){
        //遍历字符串数组
        for (String message : arr){
            //使用andThen方法连接两个Consumer接口,消费字符串
            con1.andThen(con2).accept(message);
        }
    }

    public static void main(String[] args) {
        //定义一个字符串类型的数组
        String[] arr = {"迭嘉,男" , "索子哥,男" , "索拉卡,女"};
        //调用printInfo方法,传递一个字符串数组,和两个Lambda表达式
        printInfo(arr,(message)->{
          //消费方式:对message进行切割,获取姓名,按照指定的格式输出
          String name = message.split(",")[0];
            System.out.print("姓名:"+name);
        },(message)->{
            //消费方式:对message进行切割,获取年龄,按照指定的格式输出
            String age = message.split(",")[1];
            System.out.println(",年龄:"+age+"");
        });
    }
}
复制代码

 

Predicate接口

有时候我们需要对某种类型的数据进行判断,从而得到一个boolean值结果。这时可以使用 java.util.function.Predicate 接口。

复制代码
/*
 * Predicate接口中包含一个抽象方法:
 *   boolean test(T t):用来指定数据类型进行判断的方法
 *       结果:
 *           符合条件,返回true
 *           不符合条件,返回false
 * */
public class ee {

        /*
         * 定义一个方法
         * 参数传递一个String类型的字符串
         * 传递一个Predicate中的方法test对字符串进行判断,并把判断的结果返回
         * 使用Predicate中的方法test对字符串进行判断,并把判断的结果返回
         * */
        public static boolean checkString(String s, Predicate<String> pre){
            return pre.test(s);
        }

        public static void main(String[] args) {
            //定义一个字符串
            String s = "qwerty";

            //调用checkString方法对字符串进行校验,参数传递字符串和Lambda表达式
            boolean b = checkString(s,str ->str.length() > 5);
            System.out.println(b);
        }
    }
复制代码

 

posted @   漁夫  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示