"Creating a Bounded/Ordered/No-duplicates Collection"


There was a good question on the commons-user list today about how to create a data structure to hold a list of items you have visited recently on a catalog site. I advised the use of either a Predicated CircularFifoBuffer or a LRUMap. The LRUMap is certainly easier, but the Predicated CircularFifoBuffer is more fun. Here’s the code for the LRUMap solution:

  import java.util.Iterator;
 import java.util.Map;

 import org.apache.commons.collections.map.LRUMap;

 // ...snip...
 public static void main(String[] args) {

   Map map = new LRUMap(5);

   map.put( "Page 1", "" );
   map.put( "Page 2", "" );
   map.put( "Page 3", "" );
   map.put( "Page 4", "" );
   map.put( "Page 5", "" );
   map.put( "Page 6", "" );
   map.put( "Page 7", "" );
   map.put( "Page 8", "" );
   map.put( "Page 9", "" );
   map.put( "Page 9", "" );
   map.put( "Page 1", "" );

   Iterator i = map.keySet().iterator();
   while (i.hasNext()) {
   String value = (String) i.next();
   System.out.println(value);
   }

This will print out “Page 1, Page 9, Page 8, Page 7, Page 6”. So, it ignored the duplicate 9 at the end of the list and it returned a series of keys from Most Recently Used to Least Recently Used. The Map takes care of key uniqueness, and the LRUMap discarded the Least Recently Used entries as it needed to.