Basic Java 8 Tutorial-predicate

Source: Internet
Author: User

In Java 8, predicate is a functional interface that can be applied to lambda expressions and method references. Its abstract approach is simple:

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

That is, the assertion of T, which returns TRUE or false. For example, in filter, you receive a 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);

Here's a demonstration of how to use predicate

Package predicateexample;PublicClassEmployee {PublicEmployee(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@OverridePublic StringTostring() {ReturnThis.id.toString () +" - "+This.age.toString ();To change body of generated methods, choose Tools | Templates. }PublicStatic 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;}}  

The above code defines multiple predicate, corresponding to multiple filter criteria, and starts using these assertions:

Package predicateexample;Import java.util.List;Import Java.util.function.Predicate;Import java.util.stream.Collectors;PublicClassemployeepredicates{PublicStatic predicate<employee>Isadultmale() {Return P-p.getage () >&& P.getgender (). Equalsignorecase ("M"); }PublicStatic 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;ImportStatic predicateexample.employeepredicates.*;PublicClasstestemployeepredicates {PublicStaticvoidMain(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 (Ten, GB,"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 (+)" can be get using negate () System.out.println (filteremp Loyees (Employees, Isagemorethan (+) negate ())); }}

Output:

[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]           
The regular expression is expressed as predicate

You can convert a regular expression to predicate by Pattern.compile (). Aspredicate (). Before Java 8, the method of finding a string that matches a regular rule from an array is

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

Convert to Predicat to:

Import Java.util.Arrays;Import java.util.List;Import Java.util.function.Predicate;Import Java.util.regex.Pattern;Import java.util.stream.Collectors;PublicClassRegexpredicateexample {PublicStaticvoidmain (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::p rintln);}} 
Source connection: https://www.codemore.top/cates/Backend/post/2018-05-06/predicate

Basic Java 8 Tutorial-predicate

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.