Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

5.5. Iterating Through Distinct Elements

5.5.1. Problem

You need to iterate over the unique elements in a Collection.

5.5.2. Solution

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

5.5.3. Discussion

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( );
}

5.5.4. See Also

For more information about the UniquePredicate see Recipe 4.7.


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.