O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.8. Creating a Priority Queue

Problem

You need to prioritize objects: removing higher priority objects from a Collection before lower priority objects.

Solution

Use a PriorityBuffer to hold objects to be prioritized. Objects will be removed from this Buffer according to a priority generated with a Comparator. Whenever the remove( ) method is called on this Buffer implementation, a PriorityBuffer uses the Comparator to sort its contents, returning the element of greatest priority. Using a PriorityBuffer without a Comparator causes the buffer to prioritize objects by natural order, casting each object to Comparable and comparing objects with the compareTo( ) method; all objects must implement the Comparable interface if no Comparator is supplied. The following example demonstrates the use of a PriorityBuffer without supplying a Comparator :

import java.util.*;
import org.apache.commons.collections.Buffer;
import org.apache.commons.collections.buffers.PriorityBuffer;

// Create a PriorityBuffer with no Comparator
Buffer priority = new PriortyBuffer( );
priority.add( new Long( 2 ) );
priority.add( new Long( 1 ) );
priority.add( new Long( 20 ) );
priority.add( new Long( 7 ) );
priority.add( new Long( 18 ) );
priority.add( new Long( 1 ) );

// Print the results in priority order
Iterator priorityIterator = priority.iterator( );
while( priorityIterator.hasNext( ) ) {
    Long value = (Long) priority.next( );
    System.out.prinltn( "Value: " + value );
}

The previous example removes values from ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required