001package systems.dmx.core.util;
002
003import java.util.ArrayList;
004import java.util.LinkedHashMap;
005import java.util.List;
006
007
008
009public class SequencedHashMap<K,V> extends LinkedHashMap<K,V> {
010
011    /**
012     * @param   beforeKey   the key <i>before</i> the key-value entry is put.
013     *                      If <code>null</code> the entry is put at the end.
014     *                      If non-<code>null</code> but not contained in the map an exception is thrown.
015     */
016    public void putBefore(K key, V value, K beforeKey) {
017        // collect keys of entries to shift
018        List<K> shiftKeys = new ArrayList<K>();
019        if (beforeKey != null) {
020            boolean shift = false;
021            for (K k : keySet()) {
022                if (!shift && k.equals(beforeKey)) {
023                    shift = true;
024                }
025                if (shift) {
026                    shiftKeys.add(k);
027                }
028            }
029            //
030            if (shiftKeys.isEmpty()) {
031                throw new RuntimeException("Key \"" + beforeKey + "\" not found in " + keySet());
032            }
033        }
034        //
035        put(key, value);
036        //
037        // shift entries
038        for (K k : shiftKeys) {
039            put(k, remove(k));
040        }
041    }
042}