Putting java.util to Use
Jun 22, 2012, 11:46 AM
I'm in the process of figuring out a good way to combine data from several sources into a single activity stream, which means that they should be categorized by date and then sorted by time. While that's a piece of cake with a single view, it gets hairy when you have several views, or perhaps several different types of sources entirely. Fortunately, abstract data types are here to help.
You're already using List
s and Map
s, right? For this, I decided to use Map
s and one of my personal favorites, the Set
. If you're not familiar with them, Set
s are like List
s, but only contain one of each element and don't (normally) guarantee any specific order - DocumentCollection
s are a type of Set (albeit not actually implementing the interface).
I created the categories by using a Map
with the Date
as the key and Set
s of entries as the value. That would work well enough using HashMap
s and HashSet
s, but they would require manual sorting in the XPage to display them in the right order. Fortunately, Java includes some more-specific types for this purpose: SortedMap
and SortedSet
. These are used the same way as normal Map
s and Set
s, but automatically maintain an order (based on either your own Comparator
or the "natural" ordering based on the objects' compareTo(...)
methods). Better still, the specific TreeMap
and TreeSet
implementation classes have methods to get at the keys and values, respectively, in descending order.
Once I had my collection objects picked out, all I had to do was start filling them in. I used stock Date
objects for the Map
's keys and wrote a compareTo(...)
method for the entries I'm keeping in the Set
. Then, on the containing activity stream class, I just had to write a "serializer" method to write out the current state of the objects into a List
for access.
While I may change around the way I do this (I may end up putting the category headers inline so I just use one SortedSet
for performance), it provides a pretty good example of when you can use some of Java's built-in classes to do some of the grunt work for you.