Class OrderedMap<K,​V>

java.lang.Object
squidpony.squidmath.OrderedMap<K,​V>
All Implemented Interfaces:
Serializable, Cloneable, Map<K,​V>, SortedMap<K,​V>
Direct Known Subclasses:
EnumOrderedMap, RegionMap

public class OrderedMap<K,​V>
extends Object
implements SortedMap<K,​V>, Serializable, Cloneable
A generic insertion-ordered hash map with with a fast implementation, originally from fastutil as Object2ObjectLinkedOpenHashMap but modified to support constant-time indexed access of keys, values, and entries, reordering, and optional hash strategies for unusual keys, such as arrays or usually-dense numeric values.
Instances of this class use a hash table to represent a map. The table is filled up to a specified load factor, and then doubled in size to accommodate new entries. If the table is emptied below one fourth of the load factor, it is halved in size. However, halving is not performed when deleting entries from an iterator, as it would interfere with the iteration process.
Note that clear() does not modify the hash table size. Rather, a family of trimming methods lets you control the size of the table; this is particularly useful if you reuse instances of this class.
Iterators generated by this map will enumerate pairs in the same order in which they have been added to the map (addition of pairs whose key is already present in the set does not change the iteration order). Note that this order has nothing in common with the natural order of the keys. The order is kept by means of a int-specialized list, IntVLA, and is modifiable with this class' reorder(int...) and shuffle(IRNG) methods, among other tools. It may be preferable to avoid instantiating an Iterator object and instead use a normal int-based for loop with getAt(int) called in each iteration. Though this doesn't allow easy deletion of items during iteration, it may be the fastest way to iterate through an OrderedMap.
This class implements the interface of a sorted map, so to allow easy access of the iteration order: for instance, you can get the first key in iteration order with firstKey() without having to create an iterator; however, this class partially violates the SortedMap contract because all submap methods throw an exception and comparator() returns always null.
Additional methods, such as getAndMoveToFirst(), make it easy to use instances of this class as a cache (e.g., with LRU policy).
This class allows approximately constant-time lookup of keys or values by their index in the ordering, which can allow some novel usage of the data structure. OrderedSet can be used like a list of unique elements, keeping order like a list does but also allowing rapid checks for whether an item exists in the OrderedSet, and OrderedMap can be used like that but with values associated as well (where OrderedSet uses contains(), OrderedMap uses containsKey()). You can also set the key and value at a position with putAt(Object, Object, int), or alter the key while keeping its value and index the same with alter(Object, Object). Reordering works here too, both with completely random orders from shuffle(IRNG) or with a previously-generated ordering from reorder(int...) (you can produce such an ordering for a given size and reuse it across multiple Ordered data structures with IRNG.randomOrdering(int)). Note that putAt() and removeAt(int) do not run in constant time, and depending on the point of insertion/removal, they are likely to run in linear time (but also note that most insertion-ordered Maps and Sets don't allow insertion or removal at anywhere but the beginning or end of the order).
You can pass a CrossHash.IHasher instance such as CrossHash.generalHasher as an extra parameter to most of this class' constructors, which allows the OrderedMap to use arrays (usually primitive arrays) as keys. If you expect only one type of array, you can use an instance like CrossHash.intHasher to hash int arrays, or the aforementioned generalHasher to hash most kinds of arrays (it can't handle most multi-dimensional arrays well). If you aren't using arrays as keys, you don't need to give an IHasher to the constructor and can ignore this feature most of the time. However, the default IHasher this uses if none is specified performs a small but significant "mixing" step to make the default generated hashCode() implementation many classes use into a higher-quality random-like value. This isn't always optimal; if you plan to insert 1000 sequential Integer keys with some small amount of random Integers after them, then the mixing actually increases the likelihood of a collision and takes time to calculate. You could use a very simple IHasher in that case, relying on the fact that only Integers will be added:
 new CrossHash.IHasher() {
     public int hash(Object data) { return (int)data; }
     public boolean areEqual(Object left, Object right) { return Objects.equals(left, right); }
 };
 
This is just one example of a case where a custom IHasher can be useful for performance reasons; there are also cases where an IHasher is needed to enforce hashing by identity or by value, which affect program logic. Note that the given IHasher is likely to be sub-optimal for many situations with Integer keys, and you may want to try a few different approaches if you know OrderedMap is a bottleneck in your application. If the IHasher is a performance problem, it will be at its worst if the OrderedMap needs to resize, and thus rehash, many times; this won't happen if the capacity is set correctly when the OrderedMap is created (with the capacity equal to or greater than the maximum number of entries that will be added).
Thank you, Sebastiano Vigna, for making FastUtil available to the public with such high quality.
See https://github.com/vigna/fastutil for the original library.
Author:
Sebastiano Vigna (responsible for all the hard parts), Tommy Ettinger (mostly responsible for squashing several layers of parent classes into one monster class)
See Also:
Serialized Form
  • Nested Class Summary

    Nested Classes 
    Modifier and Type Class Description
    class  OrderedMap.KeyIterator
    An iterator on keys.
    class  OrderedMap.KeySet  
    class  OrderedMap.MapEntrySet  
    class  OrderedMap.ValueCollection  
    class  OrderedMap.ValueIterator
    An iterator on values.

    Nested classes/interfaces inherited from interface java.util.Map

    Map.Entry<K extends Object,​V extends Object>
  • Field Summary

    Fields 
    Modifier and Type Field Description
    protected boolean containsNullKey
    Whether this set contains the key zero.
    static int DEFAULT_INITIAL_SIZE
    The initial default size of a hash table.
    static float DEFAULT_LOAD_FACTOR
    The default load factor of a hash table.
    protected V defRetValue
    Default return value.
    protected OrderedMap.MapEntrySet entries
    Cached set of entries.
    float f
    The acceptable load factor.
    static float FAST_LOAD_FACTOR
    The load factor for a (usually small) table that is meant to be particularly fast.
    protected CrossHash.IHasher hasher  
    protected K[] key
    The array of keys.
    protected OrderedMap.KeySet keys
    Cached set of keys.
    protected int mask
    The mask for wrapping a position counter.
    protected int maxFill
    Threshold after which we rehash.
    protected int n
    The current table size.
    protected IntVLA order
    An IntVLA (variable-length int sequence) that stores the positions in the key array of specific keys, with the positions in insertion order.
    protected int size
    Number of entries in the set (including the key zero, if present).
    protected V[] value
    The array of values.
    protected Collection<V> values
    Cached collection of values.
    static float VERY_FAST_LOAD_FACTOR
    The load factor for a (usually very small) table that is meant to be extremely fast.
  • Constructor Summary

    Constructors 
    Constructor Description
    OrderedMap()
    Creates a new OrderedMap with initial expected 16 entries and 0.75f as load factor.
    OrderedMap​(int expected)
    Creates a new OrderedMap with 0.75f as load factor.
    OrderedMap​(int expected, float f)
    Creates a new OrderedMap.
    OrderedMap​(int expected, float f, CrossHash.IHasher hasher)
    Creates a new OrderedMap.
    OrderedMap​(int expected, CrossHash.IHasher hasher)
    Creates a new OrderedMap with 0.75f as load factor.
    OrderedMap​(Collection<K> keyColl, Collection<V> valueColl)
    Creates a new OrderedMap using the elements of two parallel arrays.
    OrderedMap​(Collection<K> keyColl, Collection<V> valueColl, float f)
    Creates a new OrderedMap using the elements of two parallel arrays.
    OrderedMap​(Map<? extends K,​? extends V> m)
    Creates a new OrderedMap with 0.75f as load factor copying a given one.
    OrderedMap​(Map<? extends K,​? extends V> m, float f)
    Creates a new OrderedMap copying a given one.
    OrderedMap​(Map<? extends K,​? extends V> m, float f, CrossHash.IHasher hasher)
    Creates a new OrderedMap copying a given one.
    OrderedMap​(Map<? extends K,​? extends V> m, CrossHash.IHasher hasher)
    Creates a new OrderedMap with 0.75f as load factor copying a given one.
    OrderedMap​(K[] keyArray, V[] valueArray)
    Creates a new OrderedMap with 0.75f as load factor using the elements of two parallel arrays.
    OrderedMap​(K[] keyArray, V[] valueArray, float f)
    Creates a new OrderedMap using the elements of two parallel arrays.
    OrderedMap​(K[] keyArray, V[] valueArray, float f, CrossHash.IHasher hasher)
    Creates a new OrderedMap using the elements of two parallel arrays.
    OrderedMap​(K[] keyArray, V[] valueArray, CrossHash.IHasher hasher)
    Creates a new OrderedMap with 0.75f as load factor using the elements of two parallel arrays.
    OrderedMap​(CrossHash.IHasher hasher)
    Creates a new OrderedMap with initial expected 16 entries and 0.75f as load factor.
  • Method Summary

    Modifier and Type Method Description
    V alter​(K original, K replacement)
    Swaps a key, original, for another key, replacement, while keeping replacement at the same point in the iteration order as original and keeping it associated with the same value (which also keeps its iteration index).
    V alterAt​(int index, K replacement)
    Changes the K at the given index to replacement while keeping replacement at the same point in the ordering.
    V alterAtCarefully​(int index, K replacement)
    Changes the K at the given index to replacement while keeping replacement at the same point in the ordering.
    V alterCarefully​(K original, K replacement)
    Swaps a key, original, for another key, replacement, while keeping replacement at the same point in the iteration order as original and keeping it associated with the same value (which also keeps its iteration index).
    static int arraySize​(int expected, float f)
    Returns the least power of two smaller than or equal to 230 and larger than or equal to Math.ceil( expected / f ).
    void clear()  
    OrderedMap<K,​V> clone()
    Returns a deep copy of this map.
    Comparator<? super K> comparator()  
    boolean containsKey​(Object k)  
    boolean containsValue​(Object v)  
    V defaultReturnValue()  
    void defaultReturnValue​(V rv)  
    void ensureCapacity​(int capacity)  
    Map.Entry<K,​V> entryAt​(int idx)
    Gets the key-value Map.Entry at the given index in the iteration order in constant time (random-access).
    SortedSet<Map.Entry<K,​V>> entrySet()  
    boolean equals​(Object o)  
    K firstKey()
    Returns the first key of this map in iteration order.
    protected int fixOrder​(int i)
    Modifies the ordering so that the given entry is removed.
    protected void fixOrder​(int s, int d)
    Modifies the ordering for a shift from s to d.
    V get​(Object k)  
    V getAndMoveToFirst​(K k)
    Returns the value to which the given key is mapped; if the key is present, it is moved to the first position of the iteration order.
    V getAndMoveToLast​(K k)
    Returns the value to which the given key is mapped; if the key is present, it is moved to the last position of the iteration order.
    V getAt​(int idx)
    Gets the value at the given index in the iteration order in constant time (random-access).
    List<V> getMany​(Collection<K> keys)  
    V getOrDefault​(Object k, V defaultValue)  
    long hash64()  
    int hashCode()
    Returns a hash code for this map.
    SortedMap<K,​V> headMap​(K to)  
    int indexOf​(Object k)
    Gets the position in the ordering of the given key, though not as efficiently as some data structures can do it (e.g.
    boolean isEmpty()  
    K keyAt​(int idx)
    Gets the key at the given index in the iteration order in constant time (random-access).
    OrderedSet<K> keysAsOrderedSet()  
    SortedSet<K> keySet()  
    K lastKey()
    Returns the last key of this map in iteration order.
    static <K,​ V> OrderedMap<K,​V> makeMap()
    Makes an empty OrderedMap (OM); needs key and value types to be specified in order to work.
    static <K,​ V> OrderedMap<K,​V> makeMap​(K k0, V v0, Object... rest)
    Makes an OrderedMap (OM) with the given load factor (which should be between 0.1 and 0.9), key and value types inferred from the types of k0 and v0, and considers all remaining parameters key-value pairs, casting the Objects at positions 0, 2, 4...
    static int maxFill​(int n, float f)
    Returns the maximum number of entries that can be filled before rehashing.
    protected static <K> int objectUnwrap​(Iterator<? extends K> i, K[] array)
    Unwraps an iterator into an array.
    protected static <K> int objectUnwrap​(Iterator<? extends K> i, K[] array, int offset, int max)
    Unwraps an iterator into an array starting at a given offset for a given number of elements.
    protected int positionOf​(Object k)  
    V put​(K k, V v)  
    void putAll​(Map<? extends K,​? extends V> m)
    Puts all key-value pairs in the Map m into this OrderedMap.
    void putAll​(K[] keyArray, V[] valueArray)
    Puts the first key in keyArray with the first value in valueArray, then the second in each and so on.
    V putAndMoveToFirst​(K k, V v)
    Adds a pair to the map; if the key is already present, it is moved to the first position of the iteration order.
    V putAndMoveToLast​(K k, V v)
    Adds a pair to the map; if the key is already present, it is moved to the last position of the iteration order.
    V putAt​(K k, V v, int idx)  
    V putIfAbsent​(K key, V value)
    If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
    OrderedMap<K,​V> putPairs​(K k0, V v0, Object... rest)
    Given alternating key and value arguments in pairs, puts each key-value pair into this OrderedMap as if by calling put(Object, Object) repeatedly for each pair.
    Map.Entry<K,​V> randomEntry​(IRNG rng)
    Gets a random entry from this OrderedMap in constant time, using the given IRNG to generate a random number.
    K randomKey​(IRNG rng)
    Gets a random key from this OrderedMap in constant time, using the given IRNG to generate a random number.
    V randomValue​(IRNG rng)
    Gets a random value from this OrderedMap in constant time, using the given IRNG to generate a random number.
    protected void rehash​(int newN)
    Rehashes the map.
    V remove​(Object k)  
    boolean remove​(Object key, Object value)
    Removes the entry for the specified key only if it is currently mapped to the specified value.
    V removeAt​(int idx)
    Removes the key and value at the given index in the iteration order in not-exactly constant time (though it still should be efficient).
    protected V removeEntry​(int pos)  
    V removeFirst()
    Removes the mapping associated with the first key in iteration order.
    V removeLast()
    Removes the mapping associated with the last key in iteration order.
    protected V removeNullEntry()  
    OrderedMap<K,​V> reorder​(int... ordering)
    Given an array or varargs of replacement indices for this OrderedMap's iteration order, reorders this so the first item in the returned version is the same as getAt(ordering[0]) (with some care taken for negative or too-large indices), the second item in the returned version is the same as getAt(ordering[1]), etc.
    V replace​(K key, V value)
    Replaces the entry for the specified key only if it is currently mapped to some value.
    boolean replace​(K key, V oldValue, V newValue)
    Replaces the entry for the specified key only if currently mapped to the specified value.
    void reverse()
    Reverses the iteration order in linear time.
    protected void shiftKeys​(int pos)
    Shifts left entries with the specified hash code, starting at the specified position, and empties the resulting free entry.
    OrderedMap<K,​V> shuffle​(IRNG rng)
    Randomly alters the iteration order for this OrderedMap using the given IRNG to shuffle.
    int size()  
    void sort​(Comparator<? super K> comparator)
    Sorts this whole OrderedMap on its keys using the supplied Comparator.
    void sort​(Comparator<? super K> comparator, int start, int end)
    Sorts a sub-range of this OrderedMap on its keys from what is currently the index start up to (but not including) the index end, using the supplied Comparator.
    void sortByValue​(Comparator<? super V> comparator)
    Sorts this whole OrderedMap on its values using the supplied Comparator.
    void sortByValue​(Comparator<? super V> comparator, int start, int end)
    Sorts a sub-range of this OrderedMap on its values from what is currently the index start up to (but not including) the index end, using the supplied Comparator.
    SortedMap<K,​V> subMap​(K from, K to)  
    boolean swap​(K left, K right)
    Swaps the positions in the ordering for the given items, if they are both present.
    boolean swapIndices​(int left, int right)
    Swaps the given indices in the ordering, if they are both valid int indices.
    SortedMap<K,​V> tailMap​(K from)  
    String toString()  
    boolean trim()
    Rehashes the map, making the table as small as possible.
    boolean trim​(int n)
    Rehashes this map if the table is too large.
    protected int unwrap​(OrderedMap.ValueIterator i, Object[] array)
    Unwraps an iterator into an array.
    protected int unwrap​(OrderedMap.ValueIterator i, Object[] array, int offset, int max)
    Unwraps an iterator into an array starting at a given offset for a given number of elements.
    Collection<V> values()  
    ArrayList<V> valuesAsList()  

    Methods inherited from class java.lang.Object

    finalize, getClass, notify, notifyAll, wait, wait, wait

    Methods inherited from interface java.util.Map

    compute, computeIfAbsent, computeIfPresent, forEach, merge, replaceAll
  • Field Details

  • Constructor Details

    • OrderedMap

      public OrderedMap​(int expected, float f)
      Creates a new OrderedMap.

      The actual table size will be the least power of two greater than expected/f.

      Parameters:
      expected - the expected number of elements in the hash set.
      f - the load factor.
    • OrderedMap

      public OrderedMap​(int expected)
      Creates a new OrderedMap with 0.75f as load factor.
      Parameters:
      expected - the expected number of elements in the OrderedMap.
    • OrderedMap

      public OrderedMap()
      Creates a new OrderedMap with initial expected 16 entries and 0.75f as load factor.
    • OrderedMap

      public OrderedMap​(Map<? extends K,​? extends V> m, float f)
      Creates a new OrderedMap copying a given one.
      Parameters:
      m - a Map to be copied into the new OrderedMap.
      f - the load factor.
    • OrderedMap

      public OrderedMap​(Map<? extends K,​? extends V> m)
      Creates a new OrderedMap with 0.75f as load factor copying a given one.
      Parameters:
      m - a Map to be copied into the new OrderedMap.
    • OrderedMap

      public OrderedMap​(K[] keyArray, V[] valueArray, float f)
      Creates a new OrderedMap using the elements of two parallel arrays.
      Parameters:
      keyArray - the array of keys of the new OrderedMap.
      valueArray - the array of corresponding values in the new OrderedMap.
      f - the load factor.
      Throws:
      IllegalArgumentException - if k and v have different lengths.
    • OrderedMap

      public OrderedMap​(Collection<K> keyColl, Collection<V> valueColl)
      Creates a new OrderedMap using the elements of two parallel arrays.
      Parameters:
      keyColl - the collection of keys of the new OrderedMap.
      valueColl - the collection of corresponding values in the new OrderedMap.
      Throws:
      IllegalArgumentException - if k and v have different lengths.
    • OrderedMap

      public OrderedMap​(Collection<K> keyColl, Collection<V> valueColl, float f)
      Creates a new OrderedMap using the elements of two parallel arrays.
      Parameters:
      keyColl - the collection of keys of the new OrderedMap.
      valueColl - the collection of corresponding values in the new OrderedMap.
      f - the load factor.
      Throws:
      IllegalArgumentException - if k and v have different lengths.
    • OrderedMap

      public OrderedMap​(K[] keyArray, V[] valueArray)
      Creates a new OrderedMap with 0.75f as load factor using the elements of two parallel arrays.
      Parameters:
      keyArray - the array of keys of the new OrderedMap.
      valueArray - the array of corresponding values in the new OrderedMap.
      Throws:
      IllegalArgumentException - if k and v have different lengths.
    • OrderedMap

      public OrderedMap​(int expected, float f, CrossHash.IHasher hasher)
      Creates a new OrderedMap.

      The actual table size will be the least power of two greater than expected/f.

      Parameters:
      expected - the expected number of elements in the hash set.
      f - the load factor.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
    • OrderedMap

      public OrderedMap​(int expected, CrossHash.IHasher hasher)
      Creates a new OrderedMap with 0.75f as load factor.
      Parameters:
      expected - the expected number of elements in the OrderedMap.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
    • OrderedMap

      public OrderedMap​(CrossHash.IHasher hasher)
      Creates a new OrderedMap with initial expected 16 entries and 0.75f as load factor.
    • OrderedMap

      public OrderedMap​(Map<? extends K,​? extends V> m, float f, CrossHash.IHasher hasher)
      Creates a new OrderedMap copying a given one.
      Parameters:
      m - a Map to be copied into the new OrderedMap.
      f - the load factor.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
    • OrderedMap

      public OrderedMap​(Map<? extends K,​? extends V> m, CrossHash.IHasher hasher)
      Creates a new OrderedMap with 0.75f as load factor copying a given one.
      Parameters:
      m - a Map to be copied into the new OrderedMap.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
    • OrderedMap

      public OrderedMap​(K[] keyArray, V[] valueArray, float f, CrossHash.IHasher hasher)
      Creates a new OrderedMap using the elements of two parallel arrays.
      Parameters:
      keyArray - the array of keys of the new OrderedMap.
      valueArray - the array of corresponding values in the new OrderedMap.
      f - the load factor.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
      Throws:
      IllegalArgumentException - if k and v have different lengths.
    • OrderedMap

      public OrderedMap​(K[] keyArray, V[] valueArray, CrossHash.IHasher hasher)
      Creates a new OrderedMap with 0.75f as load factor using the elements of two parallel arrays.
      Parameters:
      keyArray - the array of keys of the new OrderedMap.
      valueArray - the array of corresponding values in the new OrderedMap.
      hasher - used to hash items; typically only needed when K is an array, where CrossHash has implementations
      Throws:
      IllegalArgumentException - if k and v have different lengths.
  • Method Details

    • defaultReturnValue

      public void defaultReturnValue​(V rv)
    • defaultReturnValue

    • ensureCapacity

      public void ensureCapacity​(int capacity)
    • removeEntry

      protected V removeEntry​(int pos)
    • removeNullEntry

      protected V removeNullEntry()
    • putAll

      public void putAll​(K[] keyArray, V[] valueArray)
      Puts the first key in keyArray with the first value in valueArray, then the second in each and so on. The entries are all appended to the end of the iteration order, unless a key was already present. Then, its value is changed at the existing position in the iteration order. If the lengths of the two arrays are not equal, this puts a number of entries equal to the lesser length. If either array is null, this returns without performing any changes.
      Parameters:
      keyArray - an array of K keys that should usually have the same length as valueArray
      valueArray - an array of V values that should usually have the same length as keyArray
    • putAll

      public void putAll​(Map<? extends K,​? extends V> m)
      Puts all key-value pairs in the Map m into this OrderedMap. The entries are all appended to the end of the iteration order, unless a key was already present. Then, its value is changed at the existing position in the iteration order. This can take any kind of Map, including unordered HashMap objects; if the Map does not have stable ordering, the order in which entries will be appended is not stable either. For this reason, OrderedMap, LinkedHashMap, and TreeMap (or other SortedMap implementations) will work best when order matters.
      Specified by:
      putAll in interface Map<K,​V>
      Parameters:
      m - a Map that should have the same or compatible K key and V value types; OrderedMap and TreeMap work best
    • put

      public V put​(K k, V v)
      Specified by:
      put in interface Map<K,​V>
    • putAt

      public V putAt​(K k, V v, int idx)
    • shiftKeys

      protected final void shiftKeys​(int pos)
      Shifts left entries with the specified hash code, starting at the specified position, and empties the resulting free entry.
      Parameters:
      pos - a starting position.
    • remove

      public V remove​(Object k)
      Specified by:
      remove in interface Map<K,​V>
    • removeFirst

      public V removeFirst()
      Removes the mapping associated with the first key in iteration order.
      Returns:
      the value previously associated with the first key in iteration order.
      Throws:
      NoSuchElementException - is this map is empty.
    • removeLast

      public V removeLast()
      Removes the mapping associated with the last key in iteration order.
      Returns:
      the value previously associated with the last key in iteration order.
      Throws:
      NoSuchElementException - is this map is empty.
    • getAndMoveToFirst

      public V getAndMoveToFirst​(K k)
      Returns the value to which the given key is mapped; if the key is present, it is moved to the first position of the iteration order.
      Parameters:
      k - the key.
      Returns:
      the corresponding value, or the default return value if no value was present for the given key.
    • getAndMoveToLast

      public V getAndMoveToLast​(K k)
      Returns the value to which the given key is mapped; if the key is present, it is moved to the last position of the iteration order.
      Parameters:
      k - the key.
      Returns:
      the corresponding value, or the default return value if no value was present for the given key.
    • putAndMoveToFirst

      public V putAndMoveToFirst​(K k, V v)
      Adds a pair to the map; if the key is already present, it is moved to the first position of the iteration order.
      Parameters:
      k - the key.
      v - the value.
      Returns:
      the old value, or the default return value if no value was present for the given key.
    • putAndMoveToLast

      public V putAndMoveToLast​(K k, V v)
      Adds a pair to the map; if the key is already present, it is moved to the last position of the iteration order.
      Parameters:
      k - the key.
      v - the value.
      Returns:
      the old value, or the default return value if no value was present for the given key.
    • get

      public V get​(Object k)
      Specified by:
      get in interface Map<K,​V>
    • getOrDefault

      public V getOrDefault​(Object k, V defaultValue)
      Specified by:
      getOrDefault in interface Map<K,​V>
    • positionOf

      protected int positionOf​(Object k)
    • indexOf

      public int indexOf​(Object k)
      Gets the position in the ordering of the given key, though not as efficiently as some data structures can do it (e.g. Arrangement can access ordering position very quickly but doesn't store other values on its own). Returns a value that is at least 0 if it found k, or -1 if k was not present.
      Parameters:
      k - a key or possible key that this should find the index of
      Returns:
      the index of k, if present, or -1 if it is not present in this OrderedMap
    • swap

      public boolean swap​(K left, K right)
      Swaps the positions in the ordering for the given items, if they are both present. Returns true if the ordering changed as a result of this call, or false if it stayed the same (which can be because left or right was not present, or because left and right are the same reference (so swapping would do nothing)).
      Parameters:
      left - an item that should be present in this OrderedMap
      right - an item that should be present in this OrderedMap
      Returns:
      true if this OrderedMap changed in ordering as a result of this call, or false otherwise
    • swapIndices

      public boolean swapIndices​(int left, int right)
      Swaps the given indices in the ordering, if they are both valid int indices. Returns true if the ordering changed as a result of this call, or false if it stayed the same (which can be because left or right referred to an out-of-bounds index, or because left and right are equal (so swapping would do nothing)).
      Parameters:
      left - an index of an item in this OrderedMap, at least 0 and less than size()
      right - an index of an item in this OrderedMap, at least 0 and less than size()
      Returns:
      true if this OrderedMap changed in ordering as a result of this call, or false otherwise
    • containsKey

      public boolean containsKey​(Object k)
      Specified by:
      containsKey in interface Map<K,​V>
    • containsValue

      public boolean containsValue​(Object v)
      Specified by:
      containsValue in interface Map<K,​V>
    • clear

      public void clear()
      Specified by:
      clear in interface Map<K,​V>
    • size

      public int size()
      Specified by:
      size in interface Map<K,​V>
    • isEmpty

      public boolean isEmpty()
      Specified by:
      isEmpty in interface Map<K,​V>
    • fixOrder

      protected int fixOrder​(int i)
      Modifies the ordering so that the given entry is removed. This method will complete in linear time.
      Parameters:
      i - the index of an entry.
      Returns:
      the iteration-order index of the removed entry
    • fixOrder

      protected void fixOrder​(int s, int d)
      Modifies the ordering for a shift from s to d.
      This method will complete in linear time unless the source position is first or last.
      Parameters:
      s - the source position.
      d - the destination position.
    • firstKey

      public K firstKey()
      Returns the first key of this map in iteration order.
      Specified by:
      firstKey in interface SortedMap<K,​V>
      Returns:
      the first key in iteration order.
    • lastKey

      public K lastKey()
      Returns the last key of this map in iteration order.
      Specified by:
      lastKey in interface SortedMap<K,​V>
      Returns:
      the last key in iteration order.
    • comparator

      public Comparator<? super K> comparator()
      Specified by:
      comparator in interface SortedMap<K,​V>
    • tailMap

      public SortedMap<K,​V> tailMap​(K from)
      Specified by:
      tailMap in interface SortedMap<K,​V>
    • headMap

      public SortedMap<K,​V> headMap​(K to)
      Specified by:
      headMap in interface SortedMap<K,​V>
    • subMap

      public SortedMap<K,​V> subMap​(K from, K to)
      Specified by:
      subMap in interface SortedMap<K,​V>
    • entrySet

      public SortedSet<Map.Entry<K,​V>> entrySet()
      Specified by:
      entrySet in interface Map<K,​V>
      Specified by:
      entrySet in interface SortedMap<K,​V>
    • keySet

      public SortedSet<K> keySet()
      Specified by:
      keySet in interface Map<K,​V>
      Specified by:
      keySet in interface SortedMap<K,​V>
    • keysAsOrderedSet

    • values

      public Collection<V> values()
      Specified by:
      values in interface Map<K,​V>
      Specified by:
      values in interface SortedMap<K,​V>
    • valuesAsList

    • trim

      public boolean trim()
      Rehashes the map, making the table as small as possible.

      This method rehashes the table to the smallest size satisfying the load factor. It can be used when the set will not be changed anymore, so to optimize access speed and size.

      If the table size is already the minimum possible, this method does nothing.

      Returns:
      true if there was enough memory to trim the map.
      See Also:
      trim(int)
    • trim

      public boolean trim​(int n)
      Rehashes this map if the table is too large.

      Let N be the smallest table size that can hold max(n,size()) entries, still satisfying the load factor. If the current table size is smaller than or equal to N, this method does nothing. Otherwise, it rehashes this map in a table of size N.

      This method is useful when reusing maps. Clearing a map leaves the table size untouched. If you are reusing a map many times, you can call this method with a typical size to avoid keeping around a very large table just because of a few large transient maps.

      Parameters:
      n - the threshold for the trimming.
      Returns:
      true if there was enough memory to trim the map.
      See Also:
      trim()
    • rehash

      protected void rehash​(int newN)
      Rehashes the map.

      This method implements the basic rehashing strategy, and may be overriden by subclasses implementing different rehashing strategies (e.g., disk-based rehashing). However, you should not override this method unless you understand the internal workings of this class.

      Parameters:
      newN - the new size
    • clone

      public OrderedMap<K,​V> clone()
      Returns a deep copy of this map.

      This method performs a deep copy of this OrderedMap; the data stored in the map, however, is not cloned. Note that this makes a difference only for object keys.

      Overrides:
      clone in class Object
      Returns:
      a deep copy of this map.
    • hashCode

      public int hashCode()
      Returns a hash code for this map. This method overrides the generic method provided by the superclass. Since equals() is not overriden, it is important that the value returned by this method is the same value as the one returned by the overriden method.
      Specified by:
      hashCode in interface Map<K,​V>
      Overrides:
      hashCode in class Object
      Returns:
      a hash code for this map.
    • hash64

      public long hash64()
    • maxFill

      public static int maxFill​(int n, float f)
      Returns the maximum number of entries that can be filled before rehashing.
      Parameters:
      n - the size of the backing array.
      f - the load factor.
      Returns:
      the maximum number of entries before rehashing.
    • arraySize

      public static int arraySize​(int expected, float f)
      Returns the least power of two smaller than or equal to 230 and larger than or equal to Math.ceil( expected / f ).
      Parameters:
      expected - the expected number of elements in a hash table.
      f - the load factor.
      Returns:
      the minimum possible size for a backing array.
      Throws:
      IllegalArgumentException - if the necessary size is larger than 230.
    • unwrap

      protected int unwrap​(OrderedMap.ValueIterator i, Object[] array, int offset, int max)
      Unwraps an iterator into an array starting at a given offset for a given number of elements.

      This method iterates over the given type-specific iterator and stores the elements returned, up to a maximum of length, in the given array starting at offset. The number of actually unwrapped elements is returned (it may be less than max if the iterator emits less than max elements).

      Parameters:
      i - a type-specific iterator.
      array - an array to contain the output of the iterator.
      offset - the first element of the array to be returned.
      max - the maximum number of elements to unwrap.
      Returns:
      the number of elements unwrapped.
    • unwrap

      protected int unwrap​(OrderedMap.ValueIterator i, Object[] array)
      Unwraps an iterator into an array.

      This method iterates over the given type-specific iterator and stores the elements returned in the given array. The iteration will stop when the iterator has no more elements or when the end of the array has been reached.

      Parameters:
      i - a type-specific iterator.
      array - an array to contain the output of the iterator.
      Returns:
      the number of elements unwrapped.
    • objectUnwrap

      protected static <K> int objectUnwrap​(Iterator<? extends K> i, K[] array, int offset, int max)
      Unwraps an iterator into an array starting at a given offset for a given number of elements.

      This method iterates over the given type-specific iterator and stores the elements returned, up to a maximum of length, in the given array starting at offset. The number of actually unwrapped elements is returned (it may be less than max if the iterator emits less than max elements).

      Parameters:
      i - a type-specific iterator.
      array - an array to contain the output of the iterator.
      offset - the first element of the array to be returned.
      max - the maximum number of elements to unwrap.
      Returns:
      the number of elements unwrapped.
    • objectUnwrap

      protected static <K> int objectUnwrap​(Iterator<? extends K> i, K[] array)
      Unwraps an iterator into an array.

      This method iterates over the given type-specific iterator and stores the elements returned in the given array. The iteration will stop when the iterator has no more elements or when the end of the array has been reached.

      Parameters:
      i - a type-specific iterator.
      array - an array to contain the output of the iterator.
      Returns:
      the number of elements unwrapped.
    • toString

      public String toString()
      Overrides:
      toString in class Object
    • equals

      public boolean equals​(Object o)
      Specified by:
      equals in interface Map<K,​V>
      Overrides:
      equals in class Object
    • getAt

      public V getAt​(int idx)
      Gets the value at the given index in the iteration order in constant time (random-access).
      Parameters:
      idx - the index in the iteration order of the value to fetch
      Returns:
      the value at the index, if the index is valid, otherwise the default return value
    • keyAt

      public K keyAt​(int idx)
      Gets the key at the given index in the iteration order in constant time (random-access).
      Parameters:
      idx - the index in the iteration order of the key to fetch
      Returns:
      the key at the index, if the index is valid, otherwise null
    • entryAt

      public Map.Entry<K,​V> entryAt​(int idx)
      Gets the key-value Map.Entry at the given index in the iteration order in constant time (random-access).
      Parameters:
      idx - the index in the iteration order of the entry to fetch
      Returns:
      the key-value entry at the index, if the index is valid, otherwise null
    • removeAt

      public V removeAt​(int idx)
      Removes the key and value at the given index in the iteration order in not-exactly constant time (though it still should be efficient).
      Parameters:
      idx - the index in the iteration order of the key and value to remove
      Returns:
      the value removed, if there was anything removed, or the default return value otherwise (often null)
    • randomValue

      public V randomValue​(IRNG rng)
      Gets a random value from this OrderedMap in constant time, using the given IRNG to generate a random number.
      Parameters:
      rng - used to generate a random index for a value
      Returns:
      a random value from this OrderedMap
    • randomKey

      public K randomKey​(IRNG rng)
      Gets a random key from this OrderedMap in constant time, using the given IRNG to generate a random number.
      Parameters:
      rng - used to generate a random index for a key
      Returns:
      a random key from this OrderedMap
    • randomEntry

      public Map.Entry<K,​V> randomEntry​(IRNG rng)
      Gets a random entry from this OrderedMap in constant time, using the given IRNG to generate a random number.
      Parameters:
      rng - used to generate a random index for a entry
      Returns:
      a random key-value entry from this OrderedMap
    • shuffle

      public OrderedMap<K,​V> shuffle​(IRNG rng)
      Randomly alters the iteration order for this OrderedMap using the given IRNG to shuffle.
      Parameters:
      rng - used to generate a random ordering
      Returns:
      this for chaining
    • reorder

      public OrderedMap<K,​V> reorder​(int... ordering)
      Given an array or varargs of replacement indices for this OrderedMap's iteration order, reorders this so the first item in the returned version is the same as getAt(ordering[0]) (with some care taken for negative or too-large indices), the second item in the returned version is the same as getAt(ordering[1]), etc.
      Negative indices are considered reversed distances from the end of ordering, so -1 refers to the same index as ordering[ordering.length - 1]. If ordering is smaller than size(), only the indices up to the length of ordering will be modified. If ordering is larger than size(), only as many indices will be affected as size(), and reversed distances are measured from the end of this Map's entries instead of the end of ordering. Duplicate values in ordering will produce duplicate values in the returned Map.
      This method modifies this OrderedMap in-place and also returns it for chaining.
      Parameters:
      ordering - an array or varargs of int indices, where the nth item in ordering changes the nth item in this Map to have the value currently in this Map at the index specified by the value in ordering
      Returns:
      this for chaining, after modifying it in-place
    • alterCarefully

      public V alterCarefully​(K original, K replacement)
      Swaps a key, original, for another key, replacement, while keeping replacement at the same point in the iteration order as original and keeping it associated with the same value (which also keeps its iteration index). Unlike the similar method alter(Object, Object), this will not change this OrderedMap if replacement is already present. To contrast, alter() can reduce the size of the OrderedMap if both original and replacement are already in the Map. If replacement is found, this returns the default return value, otherwise it switches out original for replacement and returns whatever was associated with original.
      Parameters:
      original - the key to find and swap out
      replacement - the key to replace original with
      Returns:
      the value associated with original before, and replacement now
    • alter

      public V alter​(K original, K replacement)
      Swaps a key, original, for another key, replacement, while keeping replacement at the same point in the iteration order as original and keeping it associated with the same value (which also keeps its iteration index). Be aware that if both original and replacement are present in the OrderedMap, this will still replace original with replacement but will also remove the other occurrence of replacement to avoid duplicate keys. This can throw off the expected order because the duplicate could be at any point in the ordering when it is removed. You may want to prefer alterCarefully(Object, Object) if you don't feel like checking by hand for whether replacement is already present, but using this method is perfectly reasonable if you know overlaps won't happen.
      Parameters:
      original - the key to find and swap out
      replacement - the key to replace original with
      Returns:
      the value associated with original before, and replacement now
    • getMany

      public List<V> getMany​(Collection<K> keys)
    • alterAt

      public V alterAt​(int index, K replacement)
      Changes the K at the given index to replacement while keeping replacement at the same point in the ordering. Be aware that if replacement is present in the OrderedMap, this will still replace the given index with replacement but will also remove the other occurrence of replacement to avoid duplicate keys. This can throw off the expected order because the duplicate could be at any point in the ordering when it is removed. You may want to prefer alterAtCarefully(int, Object) if you don't feel like checking by hand for whether replacement is already present, but using this method is perfectly reasonable if you know overlaps won't happen.
      Parameters:
      index - an index to replace the K key at
      replacement - another K key that will replace the original at the remembered index
      Returns:
      the value associated with the possibly-altered key
    • alterAtCarefully

      public V alterAtCarefully​(int index, K replacement)
      Changes the K at the given index to replacement while keeping replacement at the same point in the ordering. Unlike the similar method alterAt(int, Object), this will not change this OrderedMap if replacement is already present. To contrast, alterAt() can reduce the size of the OrderedMap if replacement is already in the Map. If replacement is found, this returns the default return value, otherwise it switches out the index for replacement and returns whatever value was at the index before.
      Parameters:
      index - an index to replace the K key at
      replacement - another K key that will replace the original at the remembered index
      Returns:
      the value associated with the key at the altered index before, and replacement now
    • putIfAbsent

      public V putIfAbsent​(K key, V value)
      If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
      Specified by:
      putIfAbsent in interface Map<K,​V>
      Parameters:
      key - key with which the specified value is to be associated
      value - value to be associated with the specified key
      Returns:
      the previous value associated with the specified key, or null if there was no mapping for the key. (A null return can also indicate that the map previously associated null with the key.)
    • remove

      public boolean remove​(Object key, Object value)
      Removes the entry for the specified key only if it is currently mapped to the specified value.
      Specified by:
      remove in interface Map<K,​V>
      Parameters:
      key - key with which the specified value is associated
      value - value expected to be associated with the specified key
      Returns:
      true if the value was removed
    • replace

      public boolean replace​(K key, V oldValue, V newValue)
      Replaces the entry for the specified key only if currently mapped to the specified value. The position in the iteration order is retained.
      Specified by:
      replace in interface Map<K,​V>
      Parameters:
      key - key with which the specified value is associated
      oldValue - value expected to be associated with the specified key
      newValue - value to be associated with the specified key
      Returns:
      true if the value was replaced
    • replace

      public V replace​(K key, V value)
      Replaces the entry for the specified key only if it is currently mapped to some value. Preserves the existing key's position in the iteration order.
      Specified by:
      replace in interface Map<K,​V>
      Parameters:
      key - key with which the specified value is associated
      value - value to be associated with the specified key
      Returns:
      the previous value associated with the specified key, or null if there was no mapping for the key. (A null return can also indicate that the map previously associated null with the key.)
    • putPairs

      public OrderedMap<K,​V> putPairs​(K k0, V v0, Object... rest)
      Given alternating key and value arguments in pairs, puts each key-value pair into this OrderedMap as if by calling put(Object, Object) repeatedly for each pair. This mimics the parameter syntax used for makeMap(Object, Object, Object...), and can be used to retain that style of insertion after an OrderedMap has been instantiated.
      Parameters:
      k0 - the first key to add
      v0 - the first value to add
      rest - an array or vararg of keys and values in pairs; should contain alternating K, V, K, V... elements
      Returns:
      this, after adding all viable key-value pairs given
    • makeMap

      public static <K,​ V> OrderedMap<K,​V> makeMap​(K k0, V v0, Object... rest)
      Makes an OrderedMap (OM) with the given load factor (which should be between 0.1 and 0.9), key and value types inferred from the types of k0 and v0, and considers all remaining parameters key-value pairs, casting the Objects at positions 0, 2, 4... etc. to K and the objects at positions 1, 3, 5... etc. to V. If rest has an odd-number length, then it discards the last item. If any pair of items in rest cannot be cast to the correct type of K or V, then this inserts nothing for that pair. This is similar to the makeOM method in the Maker class, but does not allow setting the load factor (since that extra parameter can muddle how javac figures out which generic types the map should use), nor does it log debug information if a cast fails. The result should be the same otherwise.
      This is named makeMap to indicate that it expects key and value parameters, unlike a Set or List. This convention may be extended to other data structures that also have static methods for instantiation.
      Type Parameters:
      K - the type of keys in the returned OrderedMap; if not specified, will be inferred from k0
      V - the type of values in the returned OrderedMap; if not specified, will be inferred from v0
      Parameters:
      k0 - the first key; used to infer the types of other keys if generic parameters aren't specified.
      v0 - the first value; used to infer the types of other values if generic parameters aren't specified.
      rest - an array or vararg of keys and values in pairs; should contain alternating K, V, K, V... elements
      Returns:
      a freshly-made OrderedMap with K keys and V values, using k0, v0, and the contents of rest to fill it
    • makeMap

      public static <K,​ V> OrderedMap<K,​V> makeMap()
      Makes an empty OrderedMap (OM); needs key and value types to be specified in order to work. For an empty OrderedMap with String keys and Coord values, you could use Maker.<String, Coord>makeOM(). Using the new keyword is probably just as easy in this case; this method is provided for completeness relative to makeMap() with 2 or more parameters.
      Type Parameters:
      K - the type of keys in the returned OrderedMap; cannot be inferred and must be specified
      V - the type of values in the returned OrderedMap; cannot be inferred and must be specified
      Returns:
      an empty OrderedMap with the given key and value types.
    • sort

      public void sort​(Comparator<? super K> comparator)
      Sorts this whole OrderedMap on its keys using the supplied Comparator.
      Parameters:
      comparator - a Comparator that can be used on the same type this uses for its keys (may need wildcards)
    • sort

      public void sort​(Comparator<? super K> comparator, int start, int end)
      Sorts a sub-range of this OrderedMap on its keys from what is currently the index start up to (but not including) the index end, using the supplied Comparator.
      Parameters:
      comparator - a Comparator that can be used on the same type this uses for its keys (may need wildcards)
      start - the first index of a key to sort (the index can change after this)
      end - the exclusive bound on the indices to sort; often this is just size()
    • sortByValue

      public void sortByValue​(Comparator<? super V> comparator)
      Sorts this whole OrderedMap on its values using the supplied Comparator.
      Parameters:
      comparator - a Comparator that can be used on the same type this uses for its values (may need wildcards)
    • sortByValue

      public void sortByValue​(Comparator<? super V> comparator, int start, int end)
      Sorts a sub-range of this OrderedMap on its values from what is currently the index start up to (but not including) the index end, using the supplied Comparator.
      Parameters:
      comparator - a Comparator that can be used on the same type this uses for its values (may need wildcards)
      start - the first index of a value to sort (the index can change after this)
      end - the exclusive bound on the indices to sort; often this is just size()
    • reverse

      public void reverse()
      Reverses the iteration order in linear time.