I think you're using the wrong data structure. You want to use an implementation of Map
and map String
(name) to Set<Event>
(unique events).
Here is how we test it:
- Create some events.
- Create
Map<String, Set<Event>
. this will allow us to map a name to unique events.
- Fill the mapping.
So first, we create a collection of events to test:
Collection<Event> events = new ArrayList<Event>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
add(new Event("FirstCategory", new Timestamp(0)));
add(new Event("FirstCategory", new Timestamp(0)));
add(new Event("FirstCategory", new Timestamp(1)));
add(new Event("SecondCategory", new Timestamp(2)));
}
};
Now we create a mapping between a name and all of it's corresponding unique events:
Map<String, Set<Event>> eventsByName = new HashMap<String, Set<Event>>();
Now we fill the mapping with unique events for each name:
for (Event e : events) {
if (!eventsByName.containsKey(e.getName())) {
// create new set by name
eventsByName.put(e.getName(), new HashSet<Event>());
}
// add event to existing Set.
// duplicates will be dropped since it's a `Set`
eventsByName.get(e.getName()).add(e);
}
Check what we got:
System.out.println(eventsByName);
Output:
{
SecondCategory=[
Event [name=SecondCategory, timestamp=1970-01-01 02:00:00.002]
],
FirstCategory=[
Event [name=FirstCategory, timestamp=1970-01-01 02:00:00.0],
Event [name=FirstCategory, timestamp=1970-01-01 02:00:00.001]
]
}
Tip 1:
To get the list of names you only need to look at the Map
's keys, which are effectively a Set
as well:
System.out.println(eventsByName.keySet());
Output:
[SecondCategory, FirstCategory]
Tip 2:
If this isn't what you expect, and you want a different definition of uniqueness, you can implement a Comparator<Event>
and use that with a TreeSet<Event>
instead of using the HashSet<Event>
which can not accept a custom Comparator
.
So if you have a class:
class EventByRandomDefinitionComparator implements Comparator<Event>{
// implementation ...
}
This is all that needs to be done when filling the mapping:
// create different comparison mechanism
Comparator<Event> comparator = new EventByRandomDefinitionComparator();
for (Event e : events) {
if (!eventsByName.containsKey(e.getName())) {
// create new set by name
// changed Set implementation to use new comparator
eventsByName.put(e.getName(), new TreeSet<Event>(comparator)));
}
// add event to existing Set.
// duplicates will be dropped since it's a `Set`
eventsByName.get(e.getName()).add(e);
}
Good luck.