Developer Notes: Apache Commons FilterIterator

Filtering the collection based on the criteria is a great advantage of FilterIterator.

package com.blogspot.ojitha.commonexamples;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.iterators.FilterIterator;

public class ListFilteringExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Person a = new Person("Smith", "Wills");
		a.setAge(39);
		Person b = new Person("Kris", "Torano");
		b.setAge(15);
		Person c = new Person("Mark","Anthony");
		c.setAge(25);
		Person d = new Person("Mad", "Max");
		d.setAge(19);
		List<Person> persons = new ArrayList<Person>();
		persons.add(a);
		persons.add(b);
		persons.add(c);
		persons.add(d);
		
		
		Predicate predicate = new AdultFilter(18);
		Iterator<Person> adults = new FilterIterator(persons.iterator(), predicate);
		for (;adults.hasNext();) {
			Person person = adults.next();
			System.out.println(person.getFirstName()+" "+person.getLastName()+" is "+person.getAge());
		}
	}	

}

class AdultFilter implements Predicate{

	private int adultAge;
	public AdultFilter(int adultAge){
		this.adultAge = adultAge;
	}
	@Override
	public boolean evaluate(Object object) {
		if (object instanceof Person){
		 	Person person = (Person) object;
		 	if (person.getAge() > adultAge) return true;
		 	else return false;
		} return false;
	}
	
}

As shown in the above list, AdultFilter defined the criteria. This is good example Smile where Apache Common’s Predicate can be used with collections. Person class has first name, last name and age as shown in the following listing.

package com.blogspot.ojitha.commonexamples;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

public class Person {
	private String firstName;
	private String lastName;
	private int age;
	
	public Person(String first, String last){
		this.firstName = first;
		this.lastName = last;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int hashCode( ) {    return HashCodeBuilder.reflectionHashCode(this);}
	public boolean equals(Object o) {    return EqualsBuilder.reflectionEquals(this, o);}

}

Hope readers will comment on this Open-mouthed smile.

Comments

Popular posts from this blog

How To: GitHub projects in Spring Tool Suite

Spring 3 Part 7: Spring with Databases

Parse the namespace based XML using Python