java8----Predicate接口的使用
生活随笔
收集整理的這篇文章主要介紹了
java8----Predicate接口的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Suppliers(生產者)
Suppliers產生一個給定的泛型類型的結果。與Functional不同的是Suppliers不接受輸入參數。
Supplier<Person> personSupplier = Person::new;
personSupplier.get(); // new Person
Consumers(消費者)
Consumers代表在一個單一的輸入參數上執行操作。
Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
greeter.accept(new Person("Luke", "Skywalker"));
//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接口的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue 好用的轮播插件之一 vue-se
- 下一篇: ADO接口简介