Total Pageviews

2013/11/15

Apache Commons Application - Predicate Chain

Requirement
If you have a collection of value object, and would like to do search just like SQL.
And you may have more complex requirement, ex. two or more search criteria.
You may can try Apache Commons CollectionUtils and BeanUtils.

Example
Prepare a bean class whose named person with 3 attributes (name, birthPlace and department)
1:  /**  
2:   *   
3:   */  
4:  package test.collection;  
5:  import java.io.Serializable;  
6:  // TODO: Auto-generated Javadoc  
7:  /**  
8:   * The Class Person.  
9:   *   
10:   * @author albert  
11:   */  
12:  public class Person implements Serializable {  
13:       /** The Constant serialVersionUID. */  
14:       private static final long serialVersionUID = -4637096033730683016L;  
15:       /** The name. */  
16:       private String name;  
17:       /** The birth place. */  
18:       private String birthPlace;  
19:       /** The department. */  
20:       private String department;  
21:       /**  
22:        * Instantiates a new person.  
23:        */  
24:       public Person() {  
25:            super();  
26:            // TODO Auto-generated constructor stub  
27:       }  
28:       /**  
29:        * Instantiates a new person.  
30:        *   
31:        * @param name  
32:        *      the name  
33:        * @param birthPlace  
34:        *      the birth place  
35:        * @param department  
36:        *      the department  
37:        */  
38:       public Person(String name, String birthPlace, String department) {  
39:            super();  
40:            this.name = name;  
41:            this.birthPlace = birthPlace;  
42:            this.department = department;  
43:       }  
44:       /**  
45:        * Gets the name.  
46:        *   
47:        * @return the name  
48:        */  
49:       public String getName() {  
50:            return name;  
51:       }  
52:       /**  
53:        * Sets the name.  
54:        *   
55:        * @param name  
56:        *      the new name  
57:        */  
58:       public void setName(String name) {  
59:            this.name = name;  
60:       }  
61:       /**  
62:        * Gets the birth place.  
63:        *   
64:        * @return the birth place  
65:        */  
66:       public String getBirthPlace() {  
67:            return birthPlace;  
68:       }  
69:       /**  
70:        * Sets the birth place.  
71:        *   
72:        * @param birthPlace  
73:        *      the new birth place  
74:        */  
75:       public void setBirthPlace(String birthPlace) {  
76:            this.birthPlace = birthPlace;  
77:       }  
78:       /**  
79:        * Gets the department.  
80:        *   
81:        * @return the department  
82:        */  
83:       public String getDepartment() {  
84:            return department;  
85:       }  
86:       /**  
87:        * Sets the department.  
88:        *   
89:        * @param department  
90:        *      the new department  
91:        */  
92:       public void setDepartment(String department) {  
93:            this.department = department;  
94:       }  
95:       /*  
96:        * (non-Javadoc)  
97:        *   
98:        * @see java.lang.Object#toString()  
99:        */  
100:       @Override  
101:       public String toString() {  
102:            return "Person [birthPlace=" + birthPlace + ", department="  
103:                      + department + ", name=" + name + "]";  
104:       }  
105:  }  

Here is our CollectionTest class to demonstrate how to do filter in collection via Apache Commons CollectionUtils and BeanUtils.
The entry point is main method.

  • Step1. Call setUpData to create test data (List of Person).
  • Step2. Call filterDataWithTwoCriteria and pass search criteria (find out the person who birthPlace is 'ChiaYi' and work at 'DEPT1' department)
1:  package test.collection;  
2:  import java.util.ArrayList;  
3:  import java.util.List;  
4:  import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;  
5:  import org.apache.commons.collections.CollectionUtils;  
6:  import org.apache.commons.collections.Predicate;  
7:  import org.apache.commons.collections.PredicateUtils;  
8:  // TODO: Auto-generated Javadoc  
9:  /**  
10:   * The Class CollectionTest.  
11:   */  
12:  public class CollectionTest {  
13:       /** The person list. */  
14:       List<Person> personList = new ArrayList<Person>();  
15:       /**  
16:        * Sets up data.  
17:        */  
18:       void setUpData() {  
19:            personList.add(new Person("Albert", "ChiaYi", "DEPT1"));  
20:            personList.add(new Person("Mandy", "Taipei", "DEPT2"));  
21:            personList.add(new Person("Alex", "ChiaYi", "DEPT1"));  
22:            personList.add(new Person("Chris", "Taipei", "DEPT1"));  
23:       }  
24:       /**  
25:        * Filter data with two criteria.  
26:        *   
27:        * @param birthPlace  
28:        *      the birth place  
29:        * @param department  
30:        *      the department  
31:        */  
32:       @SuppressWarnings("unchecked")  
33:       void filterDataWithTwoCriteria(String birthPlace, String department) {  
34:            // set up birth place predicate  
35:            BeanPropertyValueEqualsPredicate birthPlacePredicate = new BeanPropertyValueEqualsPredicate(  
36:                      "birthPlace", birthPlace);  
37:            // set up department predicate  
38:            BeanPropertyValueEqualsPredicate departmentPredicate = new BeanPropertyValueEqualsPredicate(  
39:                      "department", department);  
40:            // Create a new Predicate that returns true only if all of the specified  
41:            // predicates are true (i.e. birthPlace='ChiaYi' and department='DEPT1')  
42:            Predicate predicates = PredicateUtils.allPredicate(new Predicate[] {  
43:                      birthPlacePredicate, departmentPredicate });  
44:            // Selects all elements from input collection which match the given  
45:            // predicate into an output collection.  
46:            List<Person> persons = (List<Person>) CollectionUtils.select(  
47:                      personList, predicates);  
48:            // print the output collection  
49:            if (CollectionUtils.isNotEmpty(persons)) {  
50:                 for (Person person : persons) {  
51:                      System.out.println(person.toString());  
52:                 }  
53:            }  
54:       }  
55:       /**  
56:        * The main method.  
57:        *   
58:        * @param args  
59:        *      the arguments  
60:        */  
61:       public static void main(String[] args) {  
62:            CollectionTest test = new CollectionTest();  
63:            // Sets up data  
64:            test.setUpData();  
65:            // find the person who birth place is ChiaYi and work at DEPT1  
66:            // department  
67:            test.filterDataWithTwoCriteria("ChiaYi", "DEPT1");  
68:       }  
69:  }  

After executing this standalone Java application, the console will print the person whose birth place is 'ChiaYi' and work at 'DEPT1' department
1:  Person [birthPlace=ChiaYi, department=DEPT1, name=Albert]  
2:  Person [birthPlace=ChiaYi, department=DEPT1, name=Alex]  

No comments: