📜  带有示例的Java 8 谓词

📅  最后修改于: 2022-05-13 01:54:53.353000             🧑  作者: Mango

带有示例的Java 8 谓词

功能接口是在接口范围内只允许一个抽象方法的接口。 Java中有一些预定义的函数式接口,例如 Predicate、consumer、supplier 等。Lambda函数的返回类型(在 JDK 1.8 中引入)也是一个函数式接口。

功能接口PREDICATEJava.util 中定义。函数包。它提高了代码的可管理性,有助于分别对它们进行单元测试,并包含一些方法,例如:

  1. isEqual(Object targetRef) :返回一个谓词,根据 Objects.equals(Object, Object) 测试两个参数是否相等。
    static  Predicate isEqual(Object targetRef)
    Returns a predicate that tests if two arguments are 
    equal according to Objects.equals(Object, Object).
    T : the type of arguments to the predicate
    Parameters:
    targetRef : the object reference with which to 
    compare for equality, which may be null
    Returns: a predicate that tests if two arguments 
    are equal according to Objects.equals(Object, Object)
    
        
  2. and(Predicate other) :返回一个组合谓词,表示此谓词与另一个的短路逻辑与。
    default Predicate and(Predicate other)
    Returns a composed predicate that represents a 
    short-circuiting logical AND of this predicate and another.
    Parameters:
    other: a predicate that will be logically-ANDed with this predicate
    Returns : a composed predicate that represents the short-circuiting 
    logical AND of this predicate and the other predicate
    Throws: NullPointerException - if other is null
  3. negate() :返回一个表示该谓词的逻辑否定的谓词。
    default Predicate negate()
    Returns:a predicate that represents the logical 
    negation of this predicate
  4. or(Predicate other) :返回一个组合谓词,表示此谓词与另一个谓词的短路逻辑或。
    default Predicate or(Predicate other)
    Parameters:
    other : a predicate that will be logically-ORed with this predicate
    Returns:
    a composed predicate that represents the short-circuiting 
    logical OR of this predicate and the other predicate
    Throws : NullPointerException - if other is null
  5. test(T t) :在给定的参数上评估这个谓词。布尔测试(T t)
    test(T t) 
    Parameters:
    t - the input argument
    Returns:
    true if the input argument matches the predicate, otherwise false

例子

示例 1:简单谓词

Java
// Java program to illustrate Simple Predicate
  
import java.util.function.Predicate;
public class PredicateInterfaceExample1 {
    public static void main(String[] args)
    {
        // Creating predicate
        Predicate lesserthan = i -> (i < 18); 
  
        // Calling Predicate method
        System.out.println(lesserthan.test(10)); 
    }
}


Java
// Java program to illustrate Predicate Chaining
  
import java.util.function.Predicate;
public class PredicateInterfaceExample2 {
    public static void main(String[] args)
    {
        Predicate greaterThanTen = (i) -> i > 10;
  
        // Creating predicate
        Predicate lowerThanTwenty = (i) -> i < 20; 
        boolean result = greaterThanTen.and(lowerThanTwenty).test(15);
        System.out.println(result);
  
        // Calling Predicate method
        boolean result2 = greaterThanTen.and(lowerThanTwenty).negate().test(15);
        System.out.println(result2);
    }
}


Java
// Java program to illustrate 
// passing Predicate into function
  
import java.util.function.Predicate;
class PredicateInterfaceExample3 {
    static void pred(int number, Predicate predicate)
    {
        if (predicate.test(number)) {
            System.out.println("Number " + number);
        }
    }
    public static void main(String[] args)
    {
        pred(10, (i) -> i > 7);
    }
}


Java
// Java program to illustrate OR Predicate
  
import java.util.function.Predicate;
class PredicateInterfaceExample4 {
    public static Predicate hasLengthOf10 = new Predicate() {
        @Override
        public boolean test(String t)
        {
            return t.length() > 10;
        }
    };
  
    public static void predicate_or()
    {
  
        Predicate containsLetterA = p -> p.contains("A");
        String containsA = "And";
        boolean outcome = hasLengthOf10.or(containsLetterA).test(containsA);
        System.out.println(outcome);
    }
    public static void main(String[] args)
    {
        predicate_or();
    }
}


Java
// Java program to illustrate AND Predicate
  
import java.util.function.Predicate;
import java.util.Objects;
  
class PredicateInterfaceExample5 {
    public static Predicate hasLengthOf10 = new Predicate() {
        @Override
        public boolean test(String t)
        {
            return t.length() > 10;
        }
    };
  
    public static void predicate_and()
    {
        Predicate nonNullPredicate = Objects::nonNull;
  
        String nullString = null;
  
        boolean outcome = nonNullPredicate.and(hasLengthOf10).test(nullString);
        System.out.println(outcome);
  
        String lengthGTThan10 = "Welcome to the machine";
        boolean outcome2 = nonNullPredicate.and(hasLengthOf10).
        test(lengthGTThan10);
        System.out.println(outcome2);
    }
    public static void main(String[] args)
    {
        predicate_and();
    }
}


Java
// Java program to illustrate 
// negate Predicate
  
import java.util.function.Predicate;
class PredicateInterfaceExample6 {
    public static Predicate hasLengthOf10 = new Predicate() {
        @Override
        public boolean test(String t)
        {
            return t.length() > 10;
        }
    };
  
    public static void predicate_negate()
    {
  
        String lengthGTThan10 = "Thunderstruck is a 2012 children's "
                                + "film starring Kevin Durant";
  
        boolean outcome = hasLengthOf10.negate().test(lengthGTThan10);
        System.out.println(outcome);
    }
    public static void main(String[] args)
    {
        predicate_negate();
    }
}


Java
// Java program to demonstrate working of predicates
// on collection. The program finds all admins in an
// arrayList of users.
import java.util.function.Predicate;
import java.util.*;
class User
{
    String name, role;
    User(String a, String b) {
        name = a;
        role = b;
    }
    String getRole() { return role; }
    String getName() { return name; }    
    public String toString() {
       return "User Name : " + name + ", Role :" + role;
    }
  
    public static void main(String args[])
    {      
        List users = new ArrayList();
        users.add(new User("John", "admin"));
        users.add(new User("Peter", "member"));
        List admins = process(users, (User u) -> u.getRole().equals("admin"));
        System.out.println(admins);
    }
  
    public static List process(List users, 
                            Predicate predicate)
    {
        List result = new ArrayList();
        for (User user: users)        
            if (predicate.test(user))            
                result.add(user);
        return result;
    }
}


Java
// Java program to demonstrate working of predicates
// on collection. The program finds all admins in an
// arrayList of users.
import java.util.function.Predicate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
  
class User
{
    String name, role;
    User(String a, String b) {
        name = a;
        role = b;
    }
    String getRole() { return role; }
    String getName() { return name; } 
    public String toString() {
    return "User Name : " + name + ",
    Role :" + role;
    }
  
    public static void main(String args[])
    { 
        List users = 
            new ArrayList();
        users.add(new User("John", "admin"));
        users.add(new User("Peter", "member"));
          
    // This line uses Predicates to filter
    // out the list of users with the role "admin".
    // List admins = process(users, (User u) -> 
    // u.getRole().equals("admin"));
  
    // Replacing it with the following line 
    // using Stream API and lambda functions 
    // produces the same output
      
    // the input to the filter() is a lambda 
    // expression that returns a predicate: a 
    // boolean value for each user encountered 
    // (true if admin, false otherwise)
    List admins = users.stream()
    .filter((user) -> user.getRole().equals("admin"))
    .collect(Collectors.toList());
          
    System.out.println(admins);
    }
}



输出:
True

示例 2:谓词链接

Java

// Java program to illustrate Predicate Chaining
  
import java.util.function.Predicate;
public class PredicateInterfaceExample2 {
    public static void main(String[] args)
    {
        Predicate greaterThanTen = (i) -> i > 10;
  
        // Creating predicate
        Predicate lowerThanTwenty = (i) -> i < 20; 
        boolean result = greaterThanTen.and(lowerThanTwenty).test(15);
        System.out.println(result);
  
        // Calling Predicate method
        boolean result2 = greaterThanTen.and(lowerThanTwenty).negate().test(15);
        System.out.println(result2);
    }
}


输出:
True
False

示例 3:函数中的谓词

Java

// Java program to illustrate 
// passing Predicate into function
  
import java.util.function.Predicate;
class PredicateInterfaceExample3 {
    static void pred(int number, Predicate predicate)
    {
        if (predicate.test(number)) {
            System.out.println("Number " + number);
        }
    }
    public static void main(String[] args)
    {
        pred(10, (i) -> i > 7);
    }
}


输出:
Number 10

示例 4:谓词 OR

Java

// Java program to illustrate OR Predicate
  
import java.util.function.Predicate;
class PredicateInterfaceExample4 {
    public static Predicate hasLengthOf10 = new Predicate() {
        @Override
        public boolean test(String t)
        {
            return t.length() > 10;
        }
    };
  
    public static void predicate_or()
    {
  
        Predicate containsLetterA = p -> p.contains("A");
        String containsA = "And";
        boolean outcome = hasLengthOf10.or(containsLetterA).test(containsA);
        System.out.println(outcome);
    }
    public static void main(String[] args)
    {
        predicate_or();
    }
}


输出:
True

示例 5:谓词 AND

Java

// Java program to illustrate AND Predicate
  
import java.util.function.Predicate;
import java.util.Objects;
  
class PredicateInterfaceExample5 {
    public static Predicate hasLengthOf10 = new Predicate() {
        @Override
        public boolean test(String t)
        {
            return t.length() > 10;
        }
    };
  
    public static void predicate_and()
    {
        Predicate nonNullPredicate = Objects::nonNull;
  
        String nullString = null;
  
        boolean outcome = nonNullPredicate.and(hasLengthOf10).test(nullString);
        System.out.println(outcome);
  
        String lengthGTThan10 = "Welcome to the machine";
        boolean outcome2 = nonNullPredicate.and(hasLengthOf10).
        test(lengthGTThan10);
        System.out.println(outcome2);
    }
    public static void main(String[] args)
    {
        predicate_and();
    }
}


输出:
False
True

示例 6:谓词 negate()

Java

// Java program to illustrate 
// negate Predicate
  
import java.util.function.Predicate;
class PredicateInterfaceExample6 {
    public static Predicate hasLengthOf10 = new Predicate() {
        @Override
        public boolean test(String t)
        {
            return t.length() > 10;
        }
    };
  
    public static void predicate_negate()
    {
  
        String lengthGTThan10 = "Thunderstruck is a 2012 children's "
                                + "film starring Kevin Durant";
  
        boolean outcome = hasLengthOf10.negate().test(lengthGTThan10);
        System.out.println(outcome);
    }
    public static void main(String[] args)
    {
        predicate_negate();
    }
}


输出:
False

示例 7:集合中的谓词

Java

// Java program to demonstrate working of predicates
// on collection. The program finds all admins in an
// arrayList of users.
import java.util.function.Predicate;
import java.util.*;
class User
{
    String name, role;
    User(String a, String b) {
        name = a;
        role = b;
    }
    String getRole() { return role; }
    String getName() { return name; }    
    public String toString() {
       return "User Name : " + name + ", Role :" + role;
    }
  
    public static void main(String args[])
    {      
        List users = new ArrayList();
        users.add(new User("John", "admin"));
        users.add(new User("Peter", "member"));
        List admins = process(users, (User u) -> u.getRole().equals("admin"));
        System.out.println(admins);
    }
  
    public static List process(List users, 
                            Predicate predicate)
    {
        List result = new ArrayList();
        for (User user: users)        
            if (predicate.test(user))            
                result.add(user);
        return result;
    }
}


输出:
[User Name : John, Role :admin]

使用 Stream API 也可以实现相同的功能
和自 JDK 1.8 以来在 Collections API 之上提供的 lambda 函数。

Stream API允许对集合进行“流式传输”以进行动态处理。流允许对数据进行并发和并行计算(使用内部迭代),以支持类似数据库的操作,例如对数据进行分组和过滤(类似于 SQL 中的 GROUP BY 和 WHERE 子句)。这允许开发人员专注于“需要什么数据”而不是“如何需要数据”,因为流式传输隐藏了实现的细节并提供了结果。这是通过提供谓词作为在运行时在集合流上运行的函数的输入来完成的。在下面的示例中,我们将说明如何使用 Stream API 和谓词来过滤数据集合,如示例 7 中所实现的。

Java

// Java program to demonstrate working of predicates
// on collection. The program finds all admins in an
// arrayList of users.
import java.util.function.Predicate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
  
class User
{
    String name, role;
    User(String a, String b) {
        name = a;
        role = b;
    }
    String getRole() { return role; }
    String getName() { return name; } 
    public String toString() {
    return "User Name : " + name + ",
    Role :" + role;
    }
  
    public static void main(String args[])
    { 
        List users = 
            new ArrayList();
        users.add(new User("John", "admin"));
        users.add(new User("Peter", "member"));
          
    // This line uses Predicates to filter
    // out the list of users with the role "admin".
    // List admins = process(users, (User u) -> 
    // u.getRole().equals("admin"));
  
    // Replacing it with the following line 
    // using Stream API and lambda functions 
    // produces the same output
      
    // the input to the filter() is a lambda 
    // expression that returns a predicate: a 
    // boolean value for each user encountered 
    // (true if admin, false otherwise)
    List admins = users.stream()
    .filter((user) -> user.getRole().equals("admin"))
    .collect(Collectors.toList());
          
    System.out.println(admins);
    }
}

输出:

[User Name : John, Role :admin]