Java 8 基礎教程 - Predicate

來源:互聯網
上載者:User

標籤:err   nts   top   應用   static   OLE   rem   this   elements   

在Java 8中,Predicate是一個函數式介面,可以被應用於lambda運算式和方法引用。其抽象方法非常簡單:

/**     * Evaluates this predicate on the given argument.     *     * @param t the input argument     * @return {@code true} if the input argument matches the predicate,     * otherwise {@code false} */boolean test(T t);

即對t進行斷言,返回true或者false。 例如:在filter中 就會接收一個Predicate

/** * Returns a stream consisting of the elements of this stream that match * the given predicate. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param predicate a non-interfering stateless predicate to apply to each element to determine if it * should be included in the new returned stream. * @return the new stream */Stream<T> filter(Predicate<? super T> predicate);

下面來示範一下如何使用Predicate

package predicateExample; public class Employee { public Employee(Integer id, Integer age, String gender, String fName, String lName){ this.id = id; this.age = age; this.gender = gender; this.firstName = fName; this.lastName = lName; } private Integer id; private Integer age; private String gender; private String firstName; private String lastName; //Please generate Getter and Setters @Override public String toString() { return this.id.toString()+" - "+this.age.toString(); //To change body of generated methods, choose Tools | Templates. }public static Predicate<Employee> isAdultMale() { return p -> p.getAge() > 21 && p.getGender().equalsIgnoreCase("M");}public static Predicate<Employee> isAdultFemale() { return p -> p.getAge() > 18 && p.getGender().equalsIgnoreCase("F");}public static Predicate<Employee> isAgeMoreThan(Integer age) { return p -> p.getAge() > age;}} 

上面的代碼定義了多個Predicate,分別對應多個篩選條件,下面開始使用這些斷言:

package predicateExample; import java.util.List;import java.util.function.Predicate;import java.util.stream.Collectors; public class EmployeePredicates{ public static Predicate<Employee> isAdultMale() { return p -> p.getAge() > 21 && p.getGender().equalsIgnoreCase("M"); } public static Predicate<Employee> isAdultFemale() { return p -> p.getAge() > 18 && p.getGender().equalsIgnoreCase("F"); } public static Predicate<Employee> isAgeMoreThan(Integer age) { return p -> p.getAge() > age; } public static List<Employee> filterEmployees (List<Employee> employees, Predicate<Employee> predicate) { return employees.stream().filter( predicate ).collect(Collectors.<Employee>toList()); }} 
package predicateExample; import java.util.ArrayList;import java.util.Arrays;import java.util.List;import static predicateExample.EmployeePredicates.*; public class TestEmployeePredicates { public static void main(String[] args){ Employee e1 = new Employee(1,23,"M","Rick","Beethovan"); Employee e2 = new Employee(2,13,"F","Martina","Hengis"); Employee e3 = new Employee(3,43,"M","Ricky","Martin"); Employee e4 = new Employee(4,26,"M","Jon","Lowman"); Employee e5 = new Employee(5,19,"F","Cristine","Maria"); Employee e6 = new Employee(6,15,"M","David","Feezor"); Employee e7 = new Employee(7,68,"F","Melissa","Roy"); Employee e8 = new Employee(8,79,"M","Alex","Gussin"); Employee e9 = new Employee(9,15,"F","Neetu","Singh"); Employee e10 = new Employee(10,45,"M","Naveen","Jain"); List<Employee> employees = new ArrayList<Employee>(); employees.addAll(Arrays.asList(new Employee[]{e1,e2,e3,e4,e5,e6,e7,e8,e9,e10})); System.out.println(filterEmployees(employees, isAdultMale())); System.out.println(filterEmployees(employees, isAdultFemale())); System.out.println(filterEmployees(employees, isAgeMoreThan(35))); //Employees other than above collection of "isAgeMoreThan(35)" can be get using negate() System.out.println(filterEmployees(employees, isAgeMoreThan(35).negate())); }}

輸出:

[1 - 23, 3 - 43, 4 - 26, 8 - 79, 10 - 45][5 - 19, 7 - 68][3 - 43, 7 - 68, 8 - 79, 10 - 45][1 - 23, 2 - 13, 4 - 26, 5 - 19, 6 - 15, 9 - 15]
Regex表示為Predicate

可以通過Pattern.compile().asPredicate()將Regex轉換為Predicate。 在Java 8之前,從一個數組中找出符合正則規則的字串的方法是

public static void main(String[] args){ Pattern pattern = Pattern.compile("^(.+)@example.com$"); // Input list List<String> emails = Arrays.asList("[email protected]", "[email protected]", "[email protected]", "[email protected]"); for(String email : emails) { Matcher matcher = pattern.matcher(email); if(matcher.matches()) { System.out.println(email); } }}

轉換為Predicat為:

import java.util.Arrays;import java.util.List;import java.util.function.Predicate;import java.util.regex.Pattern;import java.util.stream.Collectors; public class RegexPredicateExample { public static void main(String[] args) { // Compile regex as predicate Predicate<String> emailFilter = Pattern .compile("^(.+)@example.com$") .asPredicate(); // Input list List<String> emails = Arrays.asList("[email protected]", "[email protected]", "[email protected]", "[email protected]"); // Apply predicate filter List<String> desiredEmails = emails .stream() .filter(emailFilter) .collect(Collectors.<String>toList()); // Now perform desired operation desiredEmails.forEach(System.out::println); }}
原文串連:https://www.codemore.top/cates/Backend/post/2018-05-06/predicate

Java 8 基礎教程 - Predicate

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.