javascript-collections-framework
    Preparing search index...

    Class TreeMap<K, V>Sealed

    A map kept in the order of its keys, stored as a balanced binary search tree: get, set, has, delete and the nearest-entry queries lowerEntry, floorEntry, ceilingEntry and higherEntry cost O(log n). The order is the natural order of the keys, or the comparator option.

    Key sameness is decided by the order alone: two keys are the same key when the comparator returns 0 for them, whatever their identity, and setting such a key keeps the stored key object and replaces only the value. Iteration, keys, values, entries, forEach, toJSON and toString visit the mappings in ascending key order. subMap, headMap and tailMap return live views of a key range, and reversed() a live view in descending order; changes through any view reach the map. Questions about keys alone go through keySet(), a live sorted set.

    In natural order, null and undefined cannot be keys, and lookups (get, has, delete, …) answer "absent" for them and for keys of another kind, as a native Map does; -0 is stored as 0. Values may be anything, undefined included. A comparator that throws or returns NaN leaves the map as it was (putAll keeps the mappings it set before the failure). A comparator that is not a consistent total order may make lookups give wrong answers, but never loses mappings or loops. Adding or removing mappings while iterating throws ConcurrentModificationError; writing a value does not.

    Two maps are equal when they have the same size and each maps every key of the other to an equal value, so a TreeMap equals a HashMap with the same mappings. The class is not designed to be subclassed.

    const prices = new TreeMap([[100, 'low'], [500, 'mid'], [900, 'high']])
    prices.floorEntry(640)?.value // 'mid': the level at or below 640
    prices.headMap(500).toJSON() // [[100, 'low']]

    const byLength = new TreeMap<string, number>({ comparator: (a, b) => a.length - b.length })
    byLength.set('bb', 1).set('cc', 2) // 'cc' is the same key as 'bb'
    byLength.toString() // "TreeMap(1) {'bb' => 2}"

    Type Parameters

    • K
    • V

    Implements

    Index
    • Creates a map in natural key order holding each mapping of entries; empty when entries is omitted, undefined or null. Every item is checked before anything is stored; of several equal keys the first key object is kept with the last value.

      Time: O(m) with at most m − 1 comparisons (one when m is 1 in natural order) for m items whose keys are strictly ascending; O(m log m) otherwise.

      Type Parameters

      • K
      • V

      Parameters

      • Optionalentries: Iterable<MapEntry<K, V> | readonly [K, V], any, any> | null

        [key, value] arrays, map entries, a native Map or another map. The comparator of a TreeMap given here is not used; pass it as an option, or call copy().

      Returns TreeMap<K, V>

      TypeError when entries is neither iterable nor null/undefined, or an item is not an array of length 2 or a map entry.

      NullElementError when, in natural order, a key is null or undefined.

      ClassCastError when, in natural order, the keys cannot be compared.

      new TreeMap([[3, 'c'], [1, 'a']]) // TreeMap(2) {1 => 'a', 3 => 'c'}
      
    • Creates an empty map with the given options.

      Time: O(1).

      Type Parameters

      • K
      • V

      Parameters

      Returns TreeMap<K, V>

      TypeError when comparator is neither undefined nor a function.

      new TreeMap<string, number>({ comparator: (a, b) => b.localeCompare(a) })
      
    • Creates a map holding each mapping of entries (empty when undefined or null), with keys ordered by options.comparator, or by natural order when it is omitted.

      Time: O(m) with at most m − 1 comparisons (one when m is 1 in natural order) for m items whose keys are strictly ascending; O(m log m) otherwise.

      Type Parameters

      • K
      • V

      Parameters

      • entries: Iterable<MapEntry<K, V> | readonly [K, V], any, any> | null | undefined

        [key, value] arrays, map entries, a native Map or another map.

      • Optionaloptions: TreeMapOptions<K>

        The options; comparator is read once.

      Returns TreeMap<K, V>

      TypeError when entries is neither iterable nor null/undefined, an item is not a pair or an entry, options is not an object, or comparator is neither undefined nor a function, or returns a non-number or NaN.

      NullElementError when, in natural order, a key is null or undefined.

      ClassCastError when, in natural order, the keys cannot be compared.

      new TreeMap([[1, 'a'], [2, 'b']], { comparator: (a, b) => b - a }) // TreeMap(2) {2 => 'b', 1 => 'a'}
      
    • get "[MAP_COLLECTION_BRAND]"(): true

      Marks maps so isMapCollection recognises them across copies of the package. Its key is not exported, so the getter is not called directly. Time: O(1).

      Returns true

    • get "[SEQUENCED_MAP_BRAND]"(): true

      Marks sequenced maps across copies of the package. Its key is not exported, so the getter is not called directly. Time: O(1).

      Returns true

    • get "[SORTED_MAP_BRAND]"(): true

      Marks sorted maps so isSortedMap recognises them across copies of the package. Its key is not exported, so the getter is not called directly. Time: O(1).

      Returns true

    • get "[toStringTag]"(): string

      'TreeMap', for Object.prototype.toString. Time: O(1).

      Returns string

    • get "[TREE_MAP_BRAND]"(): true

      Marks instances of this class so instanceof recognises them across copies of the package. Its key is not exported, so the getter is not called directly. Time: O(1).

      Returns true

    • get revision(): number

      A number that changes when a mapping is added or removed or a value is written (even the same value), and never on a read or on a call that changes nothing. Its exact values are unspecified; views share it. Time: O(1).

      Returns number

    • get size(): number

      The number of mappings. Time: O(1).

      Returns number

    • The value-equality protocol; delegates to equals. Time: as equals.

      Parameters

      • other: unknown

      Returns boolean

    • The value-equality protocol: an order-independent combination of the mappings' hashes through hash. Equal maps get the same value when their comparators treat as equal only keys hash hashes alike, as natural order does for primitives; then it is also the value of an equal default HashMap. Values are unspecified. Time: O(n) plus the hash calls.

      Parameters

      Returns number

    • Node's inspect hook: TreeMap(1) { 1 => 'a' } in console.log. Time: as toString.

      Parameters

      • depth: number | null
      • options: object
      • inspect: (value: unknown, options: object) => string

      Returns string

    • Returns an iterator over a new [key, value] array per mapping, in ascending key order, as entries() does. new Map(treeMap) copies the map this way.

      Time: O(log n) to create; O(1) amortised per step.

      Returns IterableIterator<[K, V]>

      A new iterator.

      ConcurrentModificationError (from next()) when mappings are added or removed after the iterator is created.

      for (const [key, value] of map) console.log(key, value)
      
    • Returns the entry of the least key greater than or equal to key, or undefined when there is none.

      Time: O(log n), with at most 2⌈log2(n + 1)⌉ comparisons.

      Parameters

      • key: K

        The key to search from; it need not be present.

      Returns MapEntry<K, V> | undefined

      A live entry, or undefined.

      NullElementError when, in natural order, key is null or undefined.

      ClassCastError when, in natural order, key cannot be compared with the stored keys.

      TypeError when the comparator returns a non-number or NaN.

      ConcurrentModificationError when the comparator adds or removes mappings.

      new TreeMap([[1, 'a'], [3, 'c']]).ceilingEntry(2)?.key // 3
      
    • Removes every mapping. Open iterators fail on their next step.

      Time: O(1).

      Returns void

      map.clear()
      map.size // 0
    • Returns the comparator given at construction, or undefined when the map uses natural order.

      Time: O(1).

      Returns Comparator<K> | undefined

      The comparator, or undefined.

      const byLength = (a: string, b: string) => a.length - b.length
      new TreeMap({ comparator: byLength }).comparator() === byLength // true
      new TreeMap().comparator() // undefined
    • Maps key to fn(currentValueOrUndefined, key, map), or removes the mapping when the result is undefined, and returns the result. The key is checked before fn is called.

      Time: as set, plus the call.

      Parameters

      • key: K

        The key.

      • fn: (value: V | undefined, key: K, map: MapCollection<K, V>) => V | undefined

        Computes the new value.

      Returns V | undefined

      The result of fn.

      TypeError when fn is not a function, or the comparator returns an invalid result.

      NullElementError when, in natural order, key is null or undefined.

      ClassCastError when, in natural order, key cannot be compared with the stored keys.

      ConcurrentModificationError when fn or the comparator adds or removes mappings; their changes stay and the call makes none of its own.

      Error whatever fn throws; the call inserts and changes nothing, and changes fn made stay.

      counts.compute(7, (n) => (n ?? 0) + 1)
      
    • When key is present, maps it to fn(value, key, map), or removes the mapping when the result is undefined, and returns the result; otherwise returns undefined without calling fn.

      Time: as get, plus the call.

      Parameters

      • key: K

        The key.

      • fn: (value: V, key: K, map: MapCollection<K, V>) => V | undefined

        Computes the new value.

      Returns V | undefined

      The result of fn, or undefined.

      TypeError when fn is not a function, or the comparator returns an invalid result.

      ConcurrentModificationError when fn or the comparator adds or removes mappings.

      Error whatever fn throws; the call inserts and changes nothing, and changes fn made stay.

      stock.computeIfPresent(3, (n) => (n > 1 ? n - 1 : undefined))
      
    • Returns whether some value is SameValueZero-equal to value.

      Time: O(n).

      Parameters

      • value: V

        The value to look for.

      Returns boolean

      true when a mapping has that value.

      new TreeMap([[1, 'a']]).containsValue('a') // true
      
    • Returns a new TreeMap with the same mappings and the same comparator, independent of this one (keys and values themselves are not copied). No user function is called.

      Time: O(n).

      Returns TreeMap<K, V>

      The copy.

      const copy = map.copy()
      copy.set(9, 'z') // map is unchanged
    • Removes the mapping of key and returns whether there was one. In natural order, null, undefined and keys that cannot be compared remove nothing.

      Time: as get.

      Parameters

      • key: K

        The key.

      Returns boolean

      true when a mapping was removed.

      TypeError when the comparator returns an invalid result.

      ConcurrentModificationError when the comparator adds or removes mappings.

      new TreeMap([[1, 'a']]).delete(1) // true
      
    • Returns an iterator over a new [key, value] array per mapping, in ascending key order.

      Time: O(log n) to create; O(1) amortised per step.

      Returns IterableIterator<[K, V]>

      A new iterator.

      ConcurrentModificationError (from next()) when mappings are added or removed after the iterator is created.

      [...new TreeMap([[1, 'a']]).entries()] // [[1, 'a']]
      
    • Returns a live view of the mappings as entries, in key order. An entry is a member when its key is present with an equal value; removing it removes the mapping; add, addFirst and addLast throw UnsupportedOperationError. Its getFirst/getLast return the entries of the least and greatest keys, removeFirst/removeLast remove those mappings (throwing NoSuchElementError when empty), and reversed() is the entry view of reversed(). Each call returns a new view.

      Time: O(1); the view's ends O(log n).

      Returns SequencedSet<MapEntry<K, V>>

      A new view, tagged TreeMapEntrySet.

      for (const entry of map.entrySet()) if (entry.value < 0) entry.setValue(0)
      
    • Returns whether other is a map of the same size in which every key of this map is present with a value equal under equals, and which has no key this map lacks — whatever the order, and the same both ways round, so a TreeMap equals a HashMap with the same mappings. Native Map, sets, lists and plain objects are never equal to it.

      Time: O(n log n), plus the lookups on other and the protocol methods.

      Parameters

      • other: unknown

        Any value.

      Returns boolean

      true when other is an equal map.

      ConcurrentModificationError when a value's equals changes the structure of other while it is compared (values are compared as equals(otherValue, thisValue)).

      new TreeMap([[1, 'a']]).equals(new HashMap([[1, 'a']])) // true
      
    • Returns the entry of the least key, or undefined when the map is empty. The comparator is not called.

      Time: O(log n).

      Returns MapEntry<K, V> | undefined

      A live entry, or undefined.

      new TreeMap([[2, 'b'], [1, 'a']]).firstEntry()?.key // 1
      
    • Returns the entry of the greatest key less than or equal to key, or undefined when there is none.

      Time: O(log n), with at most 2⌈log2(n + 1)⌉ comparisons.

      Parameters

      • key: K

        The key to search from; it need not be present.

      Returns MapEntry<K, V> | undefined

      A live entry, or undefined.

      NullElementError when, in natural order, key is null or undefined.

      ClassCastError when, in natural order, key cannot be compared with the stored keys.

      TypeError when the comparator returns a non-number or NaN.

      ConcurrentModificationError when the comparator adds or removes mappings.

      new TreeMap([[900, 'open'], [1300, 'lunch']]).floorEntry(1030)?.value // 'open'
      
    • Calls action(value, key, map) for each mapping in ascending key order, with this set to thisArg, as native Map does.

      Time: O(n) plus the calls.

      Parameters

      • action: (value: V, key: K, map: MapCollection<K, V>) => void

        Called with each value, its key and the map.

      • OptionalthisArg: unknown

        The this value for action.

      Returns void

      TypeError when action is not a function.

      ConcurrentModificationError when action adds or removes mappings.

      map.forEach((value, key) => console.log(key, value))
      
    • Returns the value mapped to the key that compares equal to key, or undefined when there is none. In natural order, null, undefined and keys that cannot be compared with the stored keys give undefined. Use has or getOrDefault to tell a stored undefined from absence.

      Time: O(log n), with at most 2⌈log2(n + 1)⌉ comparisons.

      Parameters

      • key: K

        The key to look up.

      Returns V | undefined

      The value, or undefined.

      TypeError when the comparator or a [compareSymbol] method returns a non-number or NaN.

      ConcurrentModificationError when the comparator adds or removes mappings.

      new TreeMap([[1, 'a']]).get(1)   // 'a'
      new TreeMap([[1, 'a']]).get('1') // undefined
    • Returns the value mapped to key when the key is present (even when that value is undefined), and fallback otherwise.

      Time: as get.

      Type Parameters

      • D

      Parameters

      • key: K

        The key to look up.

      • fallback: D

        The value to return when the key is absent.

      Returns V | D

      The mapped value, or fallback.

      TypeError when the comparator returns an invalid result.

      ConcurrentModificationError when the comparator adds or removes mappings.

      new TreeMap([[1, 'a']]).getOrDefault(2, '-') // '-'
      
    • Returns the value of key when present; otherwise maps key to value and returns value, as native Map.prototype.getOrInsert does.

      Time: as set.

      Parameters

      • key: K

        The key.

      • value: V

        The value to insert when the key is absent.

      Returns V

      The mapped value.

      NullElementError when, in natural order, key is null or undefined.

      ClassCastError when, in natural order, key cannot be compared with the stored keys.

      TypeError when the comparator returns an invalid result.

      ConcurrentModificationError when the comparator adds or removes mappings.

      groups.getOrInsert(1, []).push('a')
      
    • Returns the value of key when present, without calling fn; otherwise calls fn(key), maps key to its result and returns it, as native Map.prototype.getOrInsertComputed does. If fn set the key itself, that mapping's value is overwritten in place and its key object kept; fn may change the map without an error.

      Time: as set, plus the call, plus one more search when fn added or removed mappings.

      Parameters

      • key: K

        The key.

      • fn: (key: K) => V

        Computes the value to insert, called with this undefined.

      Returns V

      The mapped value.

      TypeError when fn is not a function (even when the key is present), or the comparator returns an invalid result.

      NullElementError when, in natural order, key is null or undefined.

      ClassCastError when, in natural order, key cannot be compared with the stored keys.

      ConcurrentModificationError when the comparator adds or removes mappings.

      Error whatever fn throws; the call inserts and changes nothing, and changes fn made stay.

      cache.getOrInsertComputed(id, (id) => load(id))
      
    • Returns whether a key that compares equal to key is present. In natural order, null, undefined and keys that cannot be compared give false.

      Time: as get.

      Parameters

      • key: K

        The key to look for.

      Returns boolean

      true when the key is present.

      TypeError when the comparator returns an invalid result.

      ConcurrentModificationError when the comparator adds or removes mappings.

      new TreeMap([[1, 'a']]).has(1) // true
      
    • Returns a live view of the mappings whose keys are less than to (or equal, with inclusive: true). Changes through the view reach this map.

      Time: O(log n) to create; as subMap for the view's operations.

      Parameters

      • to: K

        The high end of the range.

      • Optionaloptions: BoundOptions | null

        inclusive (default false); read once; undefined or null for the default.

      Returns SortedMap<K, V>

      The view, tagged TreeSubMap.

      TypeError when options is not an object, undefined or null, or inclusive is neither undefined nor a boolean.

      NullElementError when, in natural order, to is null or undefined.

      ClassCastError when, in natural order, to cannot be compared with the keys.

      new TreeMap([[1, 'a'], [2, 'b']]).headMap(2).toJSON() // [[1, 'a']]
      
    • Returns the entry of the least key greater than key, or undefined when there is none.

      Time: O(log n), with at most 2⌈log2(n + 1)⌉ comparisons.

      Parameters

      • key: K

        The key to search from; it need not be present.

      Returns MapEntry<K, V> | undefined

      A live entry, or undefined.

      NullElementError when, in natural order, key is null or undefined.

      ClassCastError when, in natural order, key cannot be compared with the stored keys.

      TypeError when the comparator returns a non-number or NaN.

      ConcurrentModificationError when the comparator adds or removes mappings.

      new TreeMap([[1, 'a'], [3, 'c']]).higherEntry(1)?.key // 3
      
    • Returns whether the map has no mappings.

      Time: O(1).

      Returns boolean

      size === 0.

      new TreeMap().isEmpty() // true
      
    • Returns an iterator over the keys in ascending order.

      Time: O(log n) to create; O(1) amortised per step.

      Returns IterableIterator<K>

      A new iterator.

      ConcurrentModificationError (from next()) when mappings are added or removed after the iterator is created.

      [...new TreeMap([[2, 'b'], [1, 'a']]).keys()] // [1, 2]
      
    • Returns a live view of the keys as a sorted set, in ascending order. It answers questions about keys alone (getFirst, floor, ceiling, …); removing a key removes its mapping; add, addFirst and addLast throw UnsupportedOperationError. Each call returns a new view.

      Time: O(1).

      Returns SortedSet<K>

      A new view, tagged TreeMapKeySet.

      const map = new TreeMap([[1, 'a'], [3, 'c']])
      map.keySet().floor(2) // 1
      map.keySet().getLast() // 3
    • Returns the entry of the greatest key, or undefined when the map is empty. The comparator is not called.

      Time: O(log n).

      Returns MapEntry<K, V> | undefined

      A live entry, or undefined.

      new TreeMap([[2, 'b'], [1, 'a']]).lastEntry()?.value // 'b'
      
    • Returns the entry of the greatest key less than key, or undefined when there is none.

      Time: O(log n), with at most 2⌈log2(n + 1)⌉ comparisons.

      Parameters

      • key: K

        The key to search from; it need not be present.

      Returns MapEntry<K, V> | undefined

      A live entry, or undefined.

      NullElementError when, in natural order, key is null or undefined.

      ClassCastError when, in natural order, key cannot be compared with the stored keys.

      TypeError when the comparator returns a non-number or NaN.

      ConcurrentModificationError when the comparator adds or removes mappings.

      new TreeMap([[1, 'a'], [3, 'c']]).lowerEntry(3)?.key // 1
      
    • Maps key to value when it is absent (even when value is undefined); otherwise to fn(old, value, key, map), removing the mapping when that result is undefined. Returns the stored value, or undefined when the mapping was removed.

      Time: as set, plus the call.

      Parameters

      • key: K

        The key.

      • value: V

        The value to store, or to combine with the present one.

      • fn: (old: V, value: V, key: K, map: MapCollection<K, V>) => V | undefined

        Combines the present value with value.

      Returns V | undefined

      The stored value, or undefined.

      TypeError when fn is not a function, or the comparator returns an invalid result.

      NullElementError when, in natural order, key is null or undefined.

      ClassCastError when, in natural order, key cannot be compared with the stored keys.

      ConcurrentModificationError when fn or the comparator adds or removes mappings.

      Error whatever fn throws; the call inserts and changes nothing, and changes fn made stay.

      for (const day of days) visits.merge(day, 1, (n, one) => n + one)
      
    • Removes the mapping of the least key and returns its entry, or returns undefined when the map is empty. The entry still reads its value; setValue on it throws IllegalStateError until the key is set again. The comparator is not called.

      Time: O(log n).

      Returns MapEntry<K, V> | undefined

      The entry of the removed mapping, or undefined.

      const next = queue.pollFirstEntry() // the earliest mapping, removed
      
    • Removes the mapping of the greatest key and returns its entry, or returns undefined when the map is empty. The comparator is not called.

      Time: O(log n).

      Returns MapEntry<K, V> | undefined

      The entry of the removed mapping, or undefined.

      new TreeMap([[1, 'a'], [2, 'b']]).pollLastEntry()?.value // 'b'
      
    • Maps key to value, as set does, and returns the previous value, or undefined when the key was absent.

      Time: as set.

      Parameters

      • key: K

        The key.

      • value: V

        The value.

      Returns V | undefined

      The previous value, or undefined.

      NullElementError when, in natural order, key is null or undefined.

      ClassCastError when, in natural order, key cannot be compared with the stored keys.

      TypeError when the comparator returns an invalid result.

      ConcurrentModificationError when the comparator adds or removes mappings.

      new TreeMap([[1, 'a']]).put(1, 'b') // 'a'
      
    • Sets every mapping of entries in order, later ones replacing earlier ones for equal keys. The whole argument is read and checked first — each item's shape and, in natural order, that every key can be compared — so map.putAll(map) is safe and bad input stores nothing; mappings set before a comparator error stay.

      Time: O(m log(n + m)) for m items.

      Parameters

      • entries: Iterable<MapEntry<K, V> | readonly [K, V]>

        [key, value] arrays, map entries, a native Map or a map.

      Returns void

      TypeError when entries is not iterable, an item is not an array of length 2 or a map entry, or the comparator returns an invalid result.

      NullElementError when, in natural order, a key is null or undefined.

      ClassCastError when, in natural order, a key cannot be compared.

      ConcurrentModificationError when the comparator adds or removes mappings.

      map.putAll(new Map([[1, 'a'], [2, 'b']]))
      
    • Always throws: a sorted map places each mapping by its key, so a mapping cannot be put at an end. Use set. Nothing is checked or changed, and the comparator is not called.

      Time: O(1).

      Parameters

      • key: K

        Ignored.

      • value: V

        Ignored.

      Returns this

      Never returns.

      UnsupportedOperationError always.

      new TreeMap<number, string>().putFirst(1, 'a') // throws UnsupportedOperationError
      
    • Always throws: a sorted map places each mapping by its key, so a mapping cannot be put at an end. Use set. Nothing is checked or changed, and the comparator is not called.

      Time: O(1).

      Parameters

      • key: K

        Ignored.

      • value: V

        Ignored.

      Returns this

      Never returns.

      UnsupportedOperationError always.

      new TreeMap<number, string>().putLast(1, 'a') // throws UnsupportedOperationError
      
    • Removes the mapping of key and returns its value, or undefined when there was none.

      Time: as get.

      Parameters

      • key: K

        The key.

      Returns V | undefined

      The removed value, or undefined.

      TypeError when the comparator returns an invalid result.

      ConcurrentModificationError when the comparator adds or removes mappings.

      new TreeMap([[1, 'a']]).remove(1) // 'a'
      
    • Replaces the value of key only when the key is present, and returns the previous value, or undefined.

      Time: as get.

      Parameters

      • key: K

        The key.

      • value: V

        The new value.

      Returns V | undefined

      The previous value, or undefined.

      TypeError when the comparator returns an invalid result.

      ConcurrentModificationError when the comparator adds or removes mappings.

      new TreeMap([[1, 'a']]).replace(2, 'b') // undefined; nothing is added
      
    • Replaces each value with fn(value, key, map), in key order. Values replaced before an error stay.

      Time: O(n) plus the calls.

      Parameters

      Returns void

      TypeError when fn is not a function.

      ConcurrentModificationError when fn adds or removes mappings.

      prices.replaceAll((price) => price * 2)
      
    • Returns a live view of this map in descending key order: its lowerEntry is this map's higherEntry, its first entry this map's last, and its ranges run from greater to lesser. Reversing the view returns this map.

      Time: O(1).

      Returns SortedMap<K, V>

      The view, tagged ReversedTreeMap.

      const map = new TreeMap([[1, 'a'], [3, 'c']])
      String(map.reversed()) // "ReversedTreeMap(2) {3 => 'c', 1 => 'a'}"
      map.reversed().reversed() === map // true
    • Maps key to value and returns the map, so calls chain. When a key that compares equal is present, its stored key object is kept and only the value is replaced. On an error nothing is stored.

      Time: O(log n), with at most 2⌈log2(n + 1)⌉ + 2 comparisons.

      Parameters

      • key: K

        The key (in natural order, -0 is stored as 0).

      • value: V

        The value.

      Returns this

      The map.

      NullElementError when, in natural order, key is null or undefined.

      ClassCastError when, in natural order, key cannot be compared with the stored keys.

      TypeError when the comparator returns a non-number or NaN.

      ConcurrentModificationError when the comparator adds or removes mappings; the map keeps those changes and stores nothing itself.

      new TreeMap<number, string>().set(2, 'b').set(1, 'a') // TreeMap(2) {1 => 'a', 2 => 'b'}
      
    • Returns a live view of the mappings whose keys run from from to to: from included and to excluded unless the options say otherwise. Changes through the view reach this map; setting a key outside the range through the view throws IllegalArgumentError, and looking one up answers absent. The view's size counts its mappings.

      Time: O(log n) to create; the view's operations cost O(log n), its size O(k + log n) for k mappings in range.

      Parameters

      • from: K

        The low end of the range.

      • to: K

        The high end of the range.

      • Optionaloptions: SubSetOptions | null

        fromInclusive (default true) and toInclusive (default false); read once; undefined or null for the defaults.

      Returns SortedMap<K, V>

      The view, tagged TreeSubMap.

      TypeError when options is not an object, undefined or null, or a flag is neither undefined nor a boolean.

      IllegalArgumentError when from is after to.

      NullElementError when, in natural order, a bound is null or undefined.

      ClassCastError when, in natural order, a bound cannot be compared with the keys.

      const map = new TreeMap([[1, 'a'], [2, 'b'], [3, 'c']])
      map.subMap(1, 3).toJSON() // [[1, 'a'], [2, 'b']]
      map.subMap(1, 3, { toInclusive: true }).size // 3
    • Returns a live view of the mappings whose keys are greater than or equal to from (or greater only, with inclusive: false). Changes through the view reach this map.

      Time: O(log n) to create; as subMap for the view's operations.

      Parameters

      • from: K

        The low end of the range.

      • Optionaloptions: BoundOptions | null

        inclusive (default true); read once; undefined or null for the default.

      Returns SortedMap<K, V>

      The view, tagged TreeSubMap.

      TypeError when options is not an object, undefined or null, or inclusive is neither undefined nor a boolean.

      NullElementError when, in natural order, from is null or undefined.

      ClassCastError when, in natural order, from cannot be compared with the keys.

      new TreeMap([[1, 'a'], [2, 'b']]).tailMap(2).toJSON() // [[2, 'b']]
      
    • Returns a new array of [key, value] arrays in ascending key order, so JSON.stringify writes the map as pairs.

      Time: O(n).

      Returns [K, V][]

      A new array.

      JSON.stringify(new TreeMap([[2, 'b'], [1, 'a']])) // '[[1,"a"],[2,"b"]]'
      
    • Returns the class name, size and mappings in ascending key order, e.g. TreeMap(2) {1 => 'a', 2 => 'b'}; a map that contains itself prints as [Circular].

      Time: O(length of the output) for flat contents.

      Returns string

      The text.

      String(new TreeMap([[2, 'b'], [1, 'a']])) // "TreeMap(2) {1 => 'a', 2 => 'b'}"
      
    • Returns a live view of the values in key order, compared with SameValueZero. delete(v) removes the mapping of the least key with that value; removeAll, retainAll and removeIf every matching mapping; add, addFirst and addLast throw UnsupportedOperationError. Its getFirst/getLast return the values of the least and greatest keys, removeFirst/removeLast remove those mappings (throwing NoSuchElementError when empty), and reversed() is the value view of reversed(). The view equals only itself. Each call returns a new view.

      Time: O(1); the view's ends O(log n).

      Returns SequencedCollection<V>

      A new view, tagged TreeMapValues.

      map.valueCollection().removeIf((v) => v === 0)
      
    • Returns an iterator over the values in ascending key order.

      Time: O(log n) to create; O(1) amortised per step.

      Returns IterableIterator<V>

      A new iterator.

      ConcurrentModificationError (from next()) when mappings are added or removed after the iterator is created.

      [...new TreeMap([[2, 'b'], [1, 'a']]).values()] // ['a', 'b']
      
    • Returns whether value is a TreeMap, including one created by another copy of the library with the same major version. Its range and reversed views are not.

      Time: O(1).

      Parameters

      • value: unknown

        The value on the left of instanceof.

      Returns boolean

      true when value is a TreeMap.

      new TreeMap() instanceof TreeMap // true
      
    • Returns a new map of the mappings of entries, with keys ordered by options.comparator, or by natural order when it is omitted. Every item is checked before anything is stored. The comparator of a TreeMap given as entries is not used.

      Time: O(m) with at most m − 1 comparisons (one when m is 1 in natural order) for m items whose keys are strictly ascending; O(m log m) otherwise.

      Type Parameters

      • K
      • V

      Parameters

      • entries: Iterable<readonly [K, V] | MapEntry<K, V>>

        [key, value] arrays, map entries, a native Map or another map; of several equal keys the first key object is kept with the last value.

      • Optionaloptions: TreeMapOptions<K>

        The options; comparator is read once.

      Returns TreeMap<K, V>

      A new map.

      TypeError when entries is not iterable (null and undefined included), an item is not a pair or an entry, options is given and is not an object, or comparator is neither undefined nor a function, or returns a non-number or NaN.

      NullElementError when, in natural order, a key is null or undefined.

      ClassCastError when, in natural order, the keys cannot be compared.

      TreeMap.from(Object.entries({ b: 2, a: 1 })).firstEntry()?.key // 'a'