Background
[wp_ad_camp_1]
You overridden your JavaBean class’ hashCode and equals methods so you can easily find (and manipulate) objects in a list. Now most properties are used in those methods. But what if you want to search for a list of objects by one or two properties only? Surely, you do not need to create a “search” object and set all its properties with values. Will you resort to loop and conditional statements? Will you modify the hashCode and equals methods? To introduce the least possible codes and/or not modify existing JavaBeans, we could use Predicate interface in conjunction with ListUtils from Apache Commons Collection.
Software Environment
- Windows 7 Professional SP1
- Eclipse – Kepler Release
- Java 1.7 (1.7.0_67 – Windows x86)
- Apache Commons Collections 4
pom.xml
1 2 3 4 5 | <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.0</version> </dependency> |
The Codes
All classes are put in a simple file – CollectionUtilsPredicateSample001.java. For brevity, the main method contains the following codes.
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public static void main(String[] args) { List<Student> listOfStudents = new ArrayList<Student>(); listOfStudents.add(new Student(1, "Smith", "Jason", "E", 98, 80, 70, 1)); listOfStudents.add(new Student(2, "Baker", "Michael", "X", 84, 82, 83, 1)); listOfStudents.add(new Student(3, "King", "Stephen", "Y", 91, 90, 71, 1)); listOfStudents.add(new Student(4, "Low", "Andrea", "P", 98, 80, 70, 1)); listOfStudents.add(new Student(5, "Martinez", "Edgardo", "P", 93, 83, 75, 1)); CustomSearchCriteria searchPredicate = new CustomSearchCriteria(); searchPredicate.setCollegeYear(1); searchPredicate.setGradeAverage(83); List<Student> filteredList = ListUtils.select(listOfStudents, searchPredicate); System.out.println("Showing search results: "); for(Student tmp: filteredList) { System.out.println(tmp); } } |
Sample Output
1 2 3 4 | Showing search results: Student [id=2, lastName=Baker, firstName=Michael, middleName=X, gradeInHistory=84, gradeInTheArts=82, gradeInChemistry=83, collegeYear=1] Student [id=3, lastName=King, firstName=Stephen, middleName=Y, gradeInHistory=91, gradeInTheArts=90, gradeInChemistry=71, collegeYear=1] Student [id=5, lastName=Martinez, firstName=Edgardo, middleName=P, gradeInHistory=93, gradeInTheArts=83, gradeInChemistry=75, collegeYear=1] |
Download the Project
[wp_ad_camp_3]
https://www.dropbox.com/s/w0p0kt6d0pqaf5f/TurretaApacheCommons.zip?dl=0