我认为您使用了错误的数据结构。您想使用Map 的实现并将String(名称)映射到Set<Event>(唯一事件)。
这是我们如何测试它:
- 创建一些事件。
- 创建
Map<String, Set<Event>。这将使我们能够将名称映射到独特事件。
- 填写映射。
首先,我们创建一个要测试的事件集合:
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)));
}
};
现在我们创建一个名称和它所有对应的唯一事件之间的映射:
Map<String, Set<Event>> eventsByName = new HashMap<String, Set<Event>>();
现在我们用每个名称的唯一事件填充映射:
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);
}
检查我们得到了什么:
System.out.println(eventsByName);
输出:
{
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]
]
}
提示 1:
要获取名称列表,您只需查看Map 的键,它们实际上也是Set:
System.out.println(eventsByName.keySet());
输出:
[SecondCategory, FirstCategory]
提示 2:
如果这不是您所期望的,并且您想要不同的唯一性定义,您可以实现 Comparator<Event> 并将其与 TreeSet<Event> 一起使用,而不是使用无法接受自定义 @ 的 HashSet<Event> 987654337@.
如果你有课:
class EventByRandomDefinitionComparator implements Comparator<Event>{
// implementation ...
}
这就是填充映射时需要做的所有事情:
// 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);
}
祝你好运。