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);