November 2004
Intermediate to advanced
400 pages
10h 31m
English
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.
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! ...
Read now
Unlock full access