I want to organize a set of Events
which have a unique id
and a time
. I want to efficiently query for Events
within particular time bounds. Some Events
might have the same time
but different id
.
Some Events
might have the same time
, so the Guava TreeMultiSet
class is really close to what I need.
However, consider the following psudo-code snippet:
class Event
{
Object id;
long time;
}
TreeMultiSet<Event> s = TreeMultiSet.create( new Comparator<Event>( )
{
@Override
public int compare( Event o1, Event o2 )
{
if ( o1.time < o2.time )
{
return -1;
}
else if ( o1.time > o2.time )
{
return 1;
}
else
{
return 0;
}
}
});
s.add( new Event( "a", 0 ) );
s.add( new Event( "b", 0 ) );
s.add( new Event( "c", 0 ) );
After the three additions, the TreeMultiSet
will just contain the "a" Event
3 times because TreeMultiSet
only considers the Comparator
and the three Event
objects have the same time
.
My first thought was to incorporate id
as part of my Comparator
implementation to distinguish between Events
with the same time
, but my ids
have no natural ordering (they're just Objects
and don't necessarily implement Comparable
).
This would also be awkward when making subSet()
, headSet()
, etc... queries -- I don't want the id
of the Event
object which I use to set the query bounds to matter.
I could implement something custom from scratch (or, more likely, delegating the heavy lifting to some underlying collections), but I wanted to make sure there wasn't something already out there which I was missing.