5.5. Iterating Through Distinct Elements
Problem
You need to iterate over the
unique elements in a Collection.
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
Discussion
The building blocks for UniqueFilterIterator have
already been introduced. FilterIterator was ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access