Use a UniqueFilterIterator to
iterate over distinct elements contained in a Collection. UniqueFilterIterator wraps another instance of
Iterator, keeping track of all the
objects returned by that Iterator.
When calling next( ) on a UniqueFilterIterator , only objects not yet encountered are returned. The
following example demonstrates the use of UniqueFilterIterator to find unique elements
in a List:
import org.apache.commons.collections.iterators.UniqueFilterIterator;
String[] medals = new String[] { "gold", "silver", "silver", "gold", "bronze" };
List medalsList = Arrays.asList( medals );
Iterator uniqueIterator = new UniqueFilterIterator( medalsList.iterator( ) );
while( uniqueIterator.hasNext( ) ) {
System.out.println( "Unique Medal: " + uniqueIterator.next( );
}UniqueFilterIterator iterates
over a List of strings, returning one
copy of each distinct element; UniqueFilterIterator uses the equals( ) and hashCode( ) methods to compare objects in the
Collection passed to the constructor.
Equal objects with equal hash codes are removed. As shown by the output
produced by the example, the UniqueFilterIterator prints out only the three
distinct medals in the medalsList:
"gold," "silver," and "bronze":
Unique Medal: gold Unique Medal: silver Unique Medal: bronze
The building blocks for UniqueFilterIterator have already been
introduced. FilterIterator was
introduced in Recipe
5.4, and UniquePredicate is a
Predicate that keeps track of objects
it has evaluated in a HashSet. A
UniqueFilterIterator is the
equivalent of a FilterIterator with a
UniquePredicate. As the following
code demonstrates, the example from the Solution can be implemented with
a FilterIterator and a Predicate:
import org.apache.commons.collections.iterators.FilterIterator;
import org.apache.commons.collections.functors.UniquePredicate;
String[] medals = new String[] { "gold", "silver", "silver", "gold", "bronze" };
List medalsList = Arrays.asList( medals );
Iterator uniqueIterator =
new FilterIterator( medalsList.iterator( ), new UniquePredicate( ) );
while( uniqueIterator.hasNext( ) ) {
System.out.println( "Unique Medal: " + uniqueIterator.next( );
}For more information about the UniquePredicate see Recipe 4.7.
