对每个值使用 aLinkedHashMap
和 an :ArrayList
LinkedHashMap<String,ArrayList<String>> phoneNumbers = new LinkedHashMap<String,ArrayList<String>>();
// register new phone number
phoneNumbers.put("1234567", new ArrayList<String>());
// add names to the phone number
phoneNumbers.get("1234567").add("AAA");
phoneNumbers.get("1234567").add("BBB");
两个集合都保留了插入顺序。
**编辑**
在这里,这大致就是您所需要的(这是在没有太多测试的情况下在现场完成的,但您应该明白这一点)。由于您的订购可能会有所不同,我认为限制重复并提供订购比较器应该是可取的(正如其他答案所建议的那样):
public class LinkedMultiMap<K,V> {
private Comparator<V> comparator;
private LinkedHashMap<K,Set<V>> entries;
public LinkedMultiMap() {
this(null);
}
public LinkedMultiMap(Comparator<V> comparator) {
this.comparator = comparator;
this.entries = new LinkedHashMap<K, Set<V>>();
}
public boolean add(K key, V value) {
if (!entries.containsKey(key)) {
entries.put(key, new TreeSet<V>(comparator));
}
return entries.get(key).add(value);
}
public Collection<V> get(K key) {
return entries.get(key);
}
public boolean remove(K key, V value) {
boolean removed = false;
if (entries.containsKey(key)) {
removed = entries.get(key).remove(value);
if (entries.get(key).isEmpty()) {
entries.remove(key);
}
}
return removed;
}
public Collection<V> removeAll(K key) {
return entries.remove(key);
}
public Iterator<K> keyIterator() {
return entries.keySet().iterator();
}
}