5.4. Filtering a Collection with a Predicate

Problem

You need to iterate through elements of a Collection that match a specified condition. Or, you have a Collection from which you need to remove elements not satisfying a condition.

Solution

Create a FilterIterator with a Predicate; if the Predicate returns true for an element, that element will be included in the Iterator. The FilterIterator decorates another Iterator and provides the ability to apply an arbitrary filter to a Collection. In the following example, EarthQuake beans are kept in an ArrayList that is filtered using the majorQuakePredicate and a FilterIterator:

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

List quakes = new ArrayList( );

EarthQuake quake1 = new EarthQuake( );
quake1.setLocation( "Chicago, IL" );
quake1.setIntensity( new Float( 6.4f ) );
quake1.setIntensity( new Float( 634.23f ) );
quake1.setTime( new Date( ) );
quakes.add( quake1 );

EarthQuake quake2 = new EarthQuake( );
quake2.setLocation( "San Francisco, CA" );
quake2.setIntensity( new Float( 4.4f ) );
quake2.setIntensity( new Float( 63.23f ) );
quake2.setTime( new Date( ) );
quakes.add( quake2 );

Predicate majorQuakePredicate = 
                   new MajorQuakePredicate( new Float(5.0), new Float(1000.0) );

               Iterator majorQuakes = 
                   new FilterIterator( quakes.iterator( ), majorQuakePredicate ); while( majorQuakes.hasMore( ) ) { EarthQuake quake = (EarthQuake) majorQuakes.next( ); System.out.println( "ALERT! ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.