码迷,mamicode.com
首页 > 编程语言 > 详细

java8----Predicate接口的使用

时间:2019-12-20 18:58:55      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:抽象   lisp   函数   asList   int   names   相等   arrays   长度   

 

 

 

 

        //5、lambda表达式中加入Predicate
        // 甚至可以用and()、or()和xor()逻辑函数来合并Predicate,
        // 例如要找到所有以J开始,长度为四个字母的名字,你可以合并两个Predicate并传入
        Predicate<String> startsWithJ = (n) -> n.startsWith("J");
        Predicate<String> fourLetterLong = (n) -> n.length() == 4;
        languages.stream()
                .filter(startsWithJ.and(fourLetterLong))
                .forEach((n) -> System.out.print("nName, which starts with ‘J‘ and four letter long is : " + n));

 

 

        //---基础用法2------------- test方法是predicate中的唯一一个抽象方法  https://www.cnblogs.com/L-a-u-r-a/p/9077615.html

        public static void filterCondition(List<String> names, Predicate<String> predicate) {
            for (String name : names) {
                if (predicate.test(name)) {
                    System.out.println(name + " ");
                }
            }
        }

        List languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");

        System.out.println("Languages which starts with J :");
        filterCondition(languages, (str) -> str.startsWith("J"));

        System.out.println("Languages which ends with a ");
        filterCondition(languages, (str) -> str.endsWith("a"));

        System.out.println("Print language whose length greater than 4:");
        filterCondition(languages, (str) -> str.length() > 4);

        System.out.println("Print all languages :");
        filterCondition(languages, (str) -> true);
        System.out.println("Print no language : ");
        filterCondition(languages, (str) -> false);

 

 

 //---基础用法------------- https://www.baidu.com/link?url=6iszXQlsmyaoWVZMaPs3g8vLRQXzdzTnKzQYTF8lg-5QQthjAu1KMSxRbEU_PznfUS4-KVH1hfn64wdAOahiCq&wd=&eqid=d6aa9d87000231f1000000065dfc8e0a

        Predicate<String> condition1 = str -> str.startsWith("j");
        Predicate<String> condition2 = str -> str.endsWith("h");
        //and
        Predicate<String> andCondition = condition1.and(condition2);
        boolean result9 = andCondition.test("jsadh");
        System.out.println(result9);//true

        //or
        Predicate<String> orCondition = condition1.or(condition2);
        result9 = orCondition.test("jasd");
        System.out.println(result9);//true

        //negate,对判断条件取反
        Predicate<String> negate = condition1.negate();
        System.out.println(negate.test("aj"));//true

        //isEqual(了解,比较两个对象是否相等)
        result9 = Predicate.isEqual("as").test("aaa");
        System.out.println(result9);

java8----Predicate接口的使用

标签:抽象   lisp   函数   asList   int   names   相等   arrays   长度   

原文地址:https://www.cnblogs.com/hahajava/p/12074308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!