001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
022import static com.google.common.collect.Maps.keyOrNull;
023
024import com.google.common.annotations.Beta;
025import com.google.common.annotations.GwtCompatible;
026import com.google.errorprone.annotations.CanIgnoreReturnValue;
027import com.google.j2objc.annotations.WeakOuter;
028import java.util.AbstractMap;
029import java.util.Arrays;
030import java.util.Comparator;
031import java.util.Map;
032import java.util.NavigableMap;
033import java.util.SortedMap;
034import java.util.Spliterator;
035import java.util.TreeMap;
036import java.util.function.BiConsumer;
037import java.util.function.BinaryOperator;
038import java.util.function.Consumer;
039import java.util.function.Function;
040import java.util.stream.Collector;
041import java.util.stream.Collectors;
042import javax.annotation.Nullable;
043
044/**
045 * A {@link NavigableMap} whose contents will never change, with many other important properties
046 * detailed at {@link ImmutableCollection}.
047 *
048 * <p><b>Warning:</b> as with any sorted collection, you are strongly advised not to use a {@link
049 * Comparator} or {@link Comparable} type whose comparison behavior is <i>inconsistent with
050 * equals</i>. That is, {@code a.compareTo(b)} or {@code comparator.compare(a, b)} should equal zero
051 * <i>if and only if</i> {@code a.equals(b)}. If this advice is not followed, the resulting map will
052 * not correctly obey its specification.
053 *
054 * <p>See the Guava User Guide article on <a href=
055 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">
056 * immutable collections</a>.
057 *
058 * @author Jared Levy
059 * @author Louis Wasserman
060 * @since 2.0 (implements {@code NavigableMap} since 12.0)
061 */
062@GwtCompatible(serializable = true, emulated = true)
063public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxverideShim<K, V>
064    implements NavigableMap<K, V> {
065  /**
066   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSortedMap}
067   * whose keys and values are the result of applying the provided mapping functions to the input
068   * elements.  The generated map is sorted by the specified comparator.
069   *
070   * <p>If the mapped keys contain duplicates (according to the specified comparator), an
071   * {@code IllegalArgumentException} is thrown when the collection operation is performed.
072   * (This differs from the {@code Collector} returned by
073   * {@link Collectors#toMap(Function, Function)}, which throws an {@code IllegalStateException}.)
074   *
075   * @since 21.0
076   */
077  @Beta
078  public static <T, K, V> Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap(
079      Comparator<? super K> comparator,
080      Function<? super T, ? extends K> keyFunction,
081      Function<? super T, ? extends V> valueFunction) {
082    return CollectCollectors.toImmutableSortedMap(comparator, keyFunction, valueFunction);
083  }
084  
085  /**
086   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSortedMap} whose
087   * keys and values are the result of applying the provided mapping functions to the input
088   * elements.
089   *
090   * <p>If the mapped keys contain duplicates (according to the comparator), the the values are
091   * merged using the specified merging function. Entries will appear in the encounter order of the
092   * first occurrence of the key.
093   *
094   * @since 21.0
095   */
096  @Beta
097  public static <T, K, V> Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap(
098      Comparator<? super K> comparator,
099      Function<? super T, ? extends K> keyFunction,
100      Function<? super T, ? extends V> valueFunction,
101      BinaryOperator<V> mergeFunction) {
102    checkNotNull(comparator);
103    checkNotNull(keyFunction);
104    checkNotNull(valueFunction);
105    checkNotNull(mergeFunction);
106    return Collectors.collectingAndThen(
107        Collectors.toMap(
108            keyFunction, valueFunction, mergeFunction, () -> new TreeMap<K, V>(comparator)),
109        ImmutableSortedMap::copyOfSorted);
110  }
111
112  /*
113   * TODO(kevinb): Confirm that ImmutableSortedMap is faster to construct and
114   * uses less memory than TreeMap; then say so in the class Javadoc.
115   */
116  private static final Comparator<Comparable> NATURAL_ORDER = Ordering.natural();
117
118  private static final ImmutableSortedMap<Comparable, Object> NATURAL_EMPTY_MAP =
119      new ImmutableSortedMap<>(
120          ImmutableSortedSet.emptySet(Ordering.natural()), ImmutableList.<Object>of());
121
122  static <K, V> ImmutableSortedMap<K, V> emptyMap(Comparator<? super K> comparator) {
123    if (Ordering.natural().equals(comparator)) {
124      return of();
125    } else {
126      return new ImmutableSortedMap<>(
127          ImmutableSortedSet.emptySet(comparator), ImmutableList.<V>of());
128    }
129  }
130
131  /**
132   * Returns the empty sorted map.
133   */
134  @SuppressWarnings("unchecked")
135  // unsafe, comparator() returns a comparator on the specified type
136  // TODO(kevinb): evaluate whether or not of().comparator() should return null
137  public static <K, V> ImmutableSortedMap<K, V> of() {
138    return (ImmutableSortedMap<K, V>) NATURAL_EMPTY_MAP;
139  }
140
141  /**
142   * Returns an immutable map containing a single entry.
143   */
144  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(K k1, V v1) {
145    return of(Ordering.natural(), k1, v1);
146  }
147
148  /**
149   * Returns an immutable map containing a single entry.
150   */
151  private static <K, V> ImmutableSortedMap<K, V> of(Comparator<? super K> comparator, K k1, V v1) {
152    return new ImmutableSortedMap<>(
153        new RegularImmutableSortedSet<K>(ImmutableList.of(k1), checkNotNull(comparator)),
154        ImmutableList.of(v1));
155  }
156
157  private static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> ofEntries(
158      Entry<K, V>... entries) {
159    return fromEntries(Ordering.natural(), false, entries, entries.length);
160  }
161
162  /**
163   * Returns an immutable sorted map containing the given entries, sorted by the
164   * natural ordering of their keys.
165   *
166   * @throws IllegalArgumentException if the two keys are equal according to
167   *     their natural ordering
168   */
169  @SuppressWarnings("unchecked")
170  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
171      K k1, V v1, K k2, V v2) {
172    return ofEntries(entryOf(k1, v1), entryOf(k2, v2));
173  }
174
175  /**
176   * Returns an immutable sorted map containing the given entries, sorted by the
177   * natural ordering of their keys.
178   *
179   * @throws IllegalArgumentException if any two keys are equal according to
180   *     their natural ordering
181   */
182  @SuppressWarnings("unchecked")
183  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
184      K k1, V v1, K k2, V v2, K k3, V v3) {
185    return ofEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
186  }
187
188  /**
189   * Returns an immutable sorted map containing the given entries, sorted by the
190   * natural ordering of their keys.
191   *
192   * @throws IllegalArgumentException if any two keys are equal according to
193   *     their natural ordering
194   */
195  @SuppressWarnings("unchecked")
196  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
197      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
198    return ofEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
199  }
200
201  /**
202   * Returns an immutable sorted map containing the given entries, sorted by the
203   * natural ordering of their keys.
204   *
205   * @throws IllegalArgumentException if any two keys are equal according to
206   *     their natural ordering
207   */
208  @SuppressWarnings("unchecked")
209  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
210      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
211    return ofEntries(
212        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
213  }
214
215  /**
216   * Returns an immutable map containing the same entries as {@code map}, sorted
217   * by the natural ordering of the keys.
218   *
219   * <p>Despite the method name, this method attempts to avoid actually copying
220   * the data when it is safe to do so. The exact circumstances under which a
221   * copy will or will not be performed are undocumented and subject to change.
222   *
223   * <p>This method is not type-safe, as it may be called on a map with keys
224   * that are not mutually comparable.
225   *
226   * @throws ClassCastException if the keys in {@code map} are not mutually
227   *         comparable
228   * @throws NullPointerException if any key or value in {@code map} is null
229   * @throws IllegalArgumentException if any two keys are equal according to
230   *         their natural ordering
231   */
232  public static <K, V> ImmutableSortedMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
233    // Hack around K not being a subtype of Comparable.
234    // Unsafe, see ImmutableSortedSetFauxverideShim.
235    @SuppressWarnings("unchecked")
236    Ordering<K> naturalOrder = (Ordering<K>) NATURAL_ORDER;
237    return copyOfInternal(map, naturalOrder);
238  }
239
240  /**
241   * Returns an immutable map containing the same entries as {@code map}, with
242   * keys sorted by the provided comparator.
243   *
244   * <p>Despite the method name, this method attempts to avoid actually copying
245   * the data when it is safe to do so. The exact circumstances under which a
246   * copy will or will not be performed are undocumented and subject to change.
247   *
248   * @throws NullPointerException if any key or value in {@code map} is null
249   * @throws IllegalArgumentException if any two keys are equal according to the
250   *         comparator
251   */
252  public static <K, V> ImmutableSortedMap<K, V> copyOf(
253      Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
254    return copyOfInternal(map, checkNotNull(comparator));
255  }
256
257  /**
258   * Returns an immutable map containing the given entries, with keys sorted
259   * by the provided comparator.
260   *
261   * <p>This method is not type-safe, as it may be called on a map with keys
262   * that are not mutually comparable.
263   *
264   * @throws NullPointerException if any key or value in {@code map} is null
265   * @throws IllegalArgumentException if any two keys are equal according to the
266   *         comparator
267   * @since 19.0
268   */
269  @Beta
270  public static <K, V> ImmutableSortedMap<K, V> copyOf(
271      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
272    // Hack around K not being a subtype of Comparable.
273    // Unsafe, see ImmutableSortedSetFauxverideShim.
274    @SuppressWarnings("unchecked")
275    Ordering<K> naturalOrder = (Ordering<K>) NATURAL_ORDER;
276    return copyOf(entries, naturalOrder);
277  }
278
279  /**
280   * Returns an immutable map containing the given entries, with keys sorted
281   * by the provided comparator.
282   *
283   * @throws NullPointerException if any key or value in {@code map} is null
284   * @throws IllegalArgumentException if any two keys are equal according to the
285   *         comparator
286   * @since 19.0
287   */
288  @Beta
289  public static <K, V> ImmutableSortedMap<K, V> copyOf(
290      Iterable<? extends Entry<? extends K, ? extends V>> entries,
291      Comparator<? super K> comparator) {
292    return fromEntries(checkNotNull(comparator), false, entries);
293  }
294
295  /**
296   * Returns an immutable map containing the same entries as the provided sorted
297   * map, with the same ordering.
298   *
299   * <p>Despite the method name, this method attempts to avoid actually copying
300   * the data when it is safe to do so. The exact circumstances under which a
301   * copy will or will not be performed are undocumented and subject to change.
302   *
303   * @throws NullPointerException if any key or value in {@code map} is null
304   */
305  @SuppressWarnings("unchecked")
306  public static <K, V> ImmutableSortedMap<K, V> copyOfSorted(SortedMap<K, ? extends V> map) {
307    Comparator<? super K> comparator = map.comparator();
308    if (comparator == null) {
309      // If map has a null comparator, the keys should have a natural ordering,
310      // even though K doesn't explicitly implement Comparable.
311      comparator = (Comparator<? super K>) NATURAL_ORDER;
312    }
313    if (map instanceof ImmutableSortedMap) {
314      // TODO(kevinb): Prove that this cast is safe, even though
315      // Collections.unmodifiableSortedMap requires the same key type.
316      @SuppressWarnings("unchecked")
317      ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map;
318      if (!kvMap.isPartialView()) {
319        return kvMap;
320      }
321    }
322    return fromEntries(comparator, true, map.entrySet());
323  }
324
325  private static <K, V> ImmutableSortedMap<K, V> copyOfInternal(
326      Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
327    boolean sameComparator = false;
328    if (map instanceof SortedMap) {
329      SortedMap<?, ?> sortedMap = (SortedMap<?, ?>) map;
330      Comparator<?> comparator2 = sortedMap.comparator();
331      sameComparator =
332          (comparator2 == null)
333              ? comparator == NATURAL_ORDER
334              : comparator.equals(comparator2);
335    }
336
337    if (sameComparator && (map instanceof ImmutableSortedMap)) {
338      // TODO(kevinb): Prove that this cast is safe, even though
339      // Collections.unmodifiableSortedMap requires the same key type.
340      @SuppressWarnings("unchecked")
341      ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map;
342      if (!kvMap.isPartialView()) {
343        return kvMap;
344      }
345    }
346    return fromEntries(comparator, sameComparator, map.entrySet());
347  }
348
349  /**
350   * Accepts a collection of possibly-null entries.  If {@code sameComparator}, then it is assumed
351   * that they do not need to be sorted or checked for dupes.
352   */
353  private static <K, V> ImmutableSortedMap<K, V> fromEntries(
354      Comparator<? super K> comparator,
355      boolean sameComparator,
356      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
357    // "adding" type params to an array of a raw type should be safe as
358    // long as no one can ever cast that same array instance back to a
359    // raw type.
360    @SuppressWarnings("unchecked")
361    Entry<K, V>[] entryArray = (Entry[]) Iterables.toArray(entries, EMPTY_ENTRY_ARRAY);
362    return fromEntries(comparator, sameComparator, entryArray, entryArray.length);
363  }
364
365  private static <K, V> ImmutableSortedMap<K, V> fromEntries(
366      final Comparator<? super K> comparator,
367      boolean sameComparator,
368      Entry<K, V>[] entryArray,
369      int size) {
370    switch (size) {
371      case 0:
372        return emptyMap(comparator);
373      case 1:
374        return ImmutableSortedMap.<K, V>of(
375            comparator, entryArray[0].getKey(), entryArray[0].getValue());
376      default:
377        Object[] keys = new Object[size];
378        Object[] values = new Object[size];
379        if (sameComparator) {
380          // Need to check for nulls, but don't need to sort or validate.
381          for (int i = 0; i < size; i++) {
382            Object key = entryArray[i].getKey();
383            Object value = entryArray[i].getValue();
384            checkEntryNotNull(key, value);
385            keys[i] = key;
386            values[i] = value;
387          }
388        } else {
389          // Need to sort and check for nulls and dupes.
390          // Inline the Comparator implementation rather than transforming with a Function
391          // to save code size.
392          Arrays.sort(
393              entryArray,
394              0,
395              size,
396              new Comparator<Entry<K, V>>() {
397                @Override
398                public int compare(Entry<K, V> e1, Entry<K, V> e2) {
399                  return comparator.compare(e1.getKey(), e2.getKey());
400                }
401              });
402          K prevKey = entryArray[0].getKey();
403          keys[0] = prevKey;
404          values[0] = entryArray[0].getValue();
405          checkEntryNotNull(keys[0], values[0]);
406          for (int i = 1; i < size; i++) {
407            K key = entryArray[i].getKey();
408            V value = entryArray[i].getValue();
409            checkEntryNotNull(key, value);
410            keys[i] = key;
411            values[i] = value;
412            checkNoConflict(
413                comparator.compare(prevKey, key) != 0, "key", entryArray[i - 1], entryArray[i]);
414            prevKey = key;
415          }
416        }
417        return new ImmutableSortedMap<>(
418            new RegularImmutableSortedSet<K>(new RegularImmutableList<K>(keys), comparator),
419            new RegularImmutableList<V>(values));
420    }
421  }
422
423  /**
424   * Returns a builder that creates immutable sorted maps whose keys are
425   * ordered by their natural ordering. The sorted maps use {@link
426   * Ordering#natural()} as the comparator.
427   */
428  public static <K extends Comparable<?>, V> Builder<K, V> naturalOrder() {
429    return new Builder<>(Ordering.natural());
430  }
431
432  /**
433   * Returns a builder that creates immutable sorted maps with an explicit
434   * comparator. If the comparator has a more general type than the map's keys,
435   * such as creating a {@code SortedMap<Integer, String>} with a {@code
436   * Comparator<Number>}, use the {@link Builder} constructor instead.
437   *
438   * @throws NullPointerException if {@code comparator} is null
439   */
440  public static <K, V> Builder<K, V> orderedBy(Comparator<K> comparator) {
441    return new Builder<>(comparator);
442  }
443
444  /**
445   * Returns a builder that creates immutable sorted maps whose keys are
446   * ordered by the reverse of their natural ordering.
447   */
448  public static <K extends Comparable<?>, V> Builder<K, V> reverseOrder() {
449    return new Builder<>(Ordering.natural().reverse());
450  }
451
452  /**
453   * A builder for creating immutable sorted map instances, especially {@code
454   * public static final} maps ("constant maps"). Example: <pre>   {@code
455   *
456   *   static final ImmutableSortedMap<Integer, String> INT_TO_WORD =
457   *       new ImmutableSortedMap.Builder<Integer, String>(Ordering.natural())
458   *           .put(1, "one")
459   *           .put(2, "two")
460   *           .put(3, "three")
461   *           .build();}</pre>
462   *
463   * <p>For <i>small</i> immutable sorted maps, the {@code ImmutableSortedMap.of()}
464   * methods are even more convenient.
465   *
466   * <p>Builder instances can be reused - it is safe to call {@link #build}
467   * multiple times to build multiple maps in series. Each map is a superset of
468   * the maps created before it.
469   *
470   * @since 2.0
471   */
472  public static class Builder<K, V> extends ImmutableMap.Builder<K, V> {
473    private final Comparator<? super K> comparator;
474
475    /**
476     * Creates a new builder. The returned builder is equivalent to the builder
477     * generated by {@link ImmutableSortedMap#orderedBy}.
478     */
479    @SuppressWarnings("unchecked")
480    public Builder(Comparator<? super K> comparator) {
481      this.comparator = checkNotNull(comparator);
482    }
483
484    /**
485     * Associates {@code key} with {@code value} in the built map. Duplicate
486     * keys, according to the comparator (which might be the keys' natural
487     * order), are not allowed, and will cause {@link #build} to fail.
488     */
489    @CanIgnoreReturnValue
490    @Override
491    public Builder<K, V> put(K key, V value) {
492      super.put(key, value);
493      return this;
494    }
495
496    /**
497     * Adds the given {@code entry} to the map, making it immutable if
498     * necessary. Duplicate keys, according to the comparator (which might be
499     * the keys' natural order), are not allowed, and will cause {@link #build}
500     * to fail.
501     *
502     * @since 11.0
503     */
504    @CanIgnoreReturnValue
505    @Override
506    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
507      super.put(entry);
508      return this;
509    }
510
511    /**
512     * Associates all of the given map's keys and values in the built map.
513     * Duplicate keys, according to the comparator (which might be the keys'
514     * natural order), are not allowed, and will cause {@link #build} to fail.
515     *
516     * @throws NullPointerException if any key or value in {@code map} is null
517     */
518    @CanIgnoreReturnValue
519    @Override
520    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
521      super.putAll(map);
522      return this;
523    }
524
525    /**
526     * Adds all the given entries to the built map.  Duplicate keys, according
527     * to the comparator (which might be the keys' natural order), are not
528     * allowed, and will cause {@link #build} to fail.
529     *
530     * @throws NullPointerException if any key, value, or entry is null
531     * @since 19.0
532     */
533    @CanIgnoreReturnValue
534    @Beta
535    @Override
536    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
537      super.putAll(entries);
538      return this;
539    }
540
541    /**
542     * Throws an {@code UnsupportedOperationException}.
543     *
544     * @since 19.0
545     * @deprecated Unsupported by ImmutableSortedMap.Builder.
546     */
547    @CanIgnoreReturnValue
548    @Beta
549    @Override
550    @Deprecated
551    public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
552      throw new UnsupportedOperationException("Not available on ImmutableSortedMap.Builder");
553    }
554
555    @Override
556    Builder<K, V> combine(ImmutableMap.Builder<K, V> other) {
557      super.combine(other);
558      return this;
559    }
560
561    /**
562     * Returns a newly-created immutable sorted map.
563     *
564     * @throws IllegalArgumentException if any two keys are equal according to
565     *     the comparator (which might be the keys' natural order)
566     */
567    @Override
568    public ImmutableSortedMap<K, V> build() {
569      switch (size) {
570        case 0:
571          return emptyMap(comparator);
572        case 1:
573          return of(comparator, entries[0].getKey(), entries[0].getValue());
574        default:
575          return fromEntries(comparator, false, entries, size);
576      }
577    }
578  }
579
580  private final transient RegularImmutableSortedSet<K> keySet;
581  private final transient ImmutableList<V> valueList;
582  private transient ImmutableSortedMap<K, V> descendingMap;
583
584  ImmutableSortedMap(RegularImmutableSortedSet<K> keySet, ImmutableList<V> valueList) {
585    this(keySet, valueList, null);
586  }
587
588  ImmutableSortedMap(
589      RegularImmutableSortedSet<K> keySet,
590      ImmutableList<V> valueList,
591      ImmutableSortedMap<K, V> descendingMap) {
592    this.keySet = keySet;
593    this.valueList = valueList;
594    this.descendingMap = descendingMap;
595  }
596
597  @Override
598  public int size() {
599    return valueList.size();
600  }
601
602  @Override
603  public void forEach(BiConsumer<? super K, ? super V> action) {
604    checkNotNull(action);
605    ImmutableList<K> keyList = keySet.asList();
606    for (int i = 0; i < size(); i++) {
607      action.accept(keyList.get(i), valueList.get(i));
608    }
609  }
610
611  @Override
612  public V get(@Nullable Object key) {
613    int index = keySet.indexOf(key);
614    return (index == -1) ? null : valueList.get(index);
615  }
616
617  @Override
618  boolean isPartialView() {
619    return keySet.isPartialView() || valueList.isPartialView();
620  }
621
622  /**
623   * Returns an immutable set of the mappings in this map, sorted by the key
624   * ordering.
625   */
626  @Override
627  public ImmutableSet<Entry<K, V>> entrySet() {
628    return super.entrySet();
629  }
630
631  @Override
632  ImmutableSet<Entry<K, V>> createEntrySet() {
633    @WeakOuter
634    class EntrySet extends ImmutableMapEntrySet<K, V> {
635      @Override
636      public UnmodifiableIterator<Entry<K, V>> iterator() {
637        return asList().iterator();
638      }
639
640      @Override
641      public Spliterator<Entry<K, V>> spliterator() {
642        return asList().spliterator();
643      }
644
645      @Override
646      public void forEach(Consumer<? super Entry<K, V>> action) {
647        asList().forEach(action);
648      }
649
650      @Override
651      ImmutableList<Entry<K, V>> createAsList() {
652        return new ImmutableAsList<Entry<K, V>>() {
653          @Override
654          public Entry<K, V> get(int index) {
655            return new AbstractMap.SimpleImmutableEntry<>(
656                keySet.asList().get(index), valueList.get(index));
657          }
658
659          @Override
660          public Spliterator<Entry<K, V>> spliterator() {
661            return CollectSpliterators.indexed(
662                size(), ImmutableSet.SPLITERATOR_CHARACTERISTICS, this::get);
663          }
664
665          @Override
666          ImmutableCollection<Entry<K, V>> delegateCollection() {
667            return EntrySet.this;
668          }
669        };
670      }
671
672      @Override
673      ImmutableMap<K, V> map() {
674        return ImmutableSortedMap.this;
675      }
676    }
677    return isEmpty() ? ImmutableSet.<Entry<K, V>>of() : new EntrySet();
678  }
679
680  /**
681   * Returns an immutable sorted set of the keys in this map.
682   */
683  @Override
684  public ImmutableSortedSet<K> keySet() {
685    return keySet;
686  }
687
688  @Override
689  ImmutableSet<K> createKeySet() {
690    throw new AssertionError("should never be called");
691  }
692
693  /**
694   * Returns an immutable collection of the values in this map, sorted by the
695   * ordering of the corresponding keys.
696   */
697  @Override
698  public ImmutableCollection<V> values() {
699    return valueList;
700  }
701
702  @Override
703  ImmutableCollection<V> createValues() {
704    throw new AssertionError("should never be called");
705  }
706
707  /**
708   * Returns the comparator that orders the keys, which is
709   * {@link Ordering#natural()} when the natural ordering of the keys is used.
710   * Note that its behavior is not consistent with {@link TreeMap#comparator()},
711   * which returns {@code null} to indicate natural ordering.
712   */
713  @Override
714  public Comparator<? super K> comparator() {
715    return keySet().comparator();
716  }
717
718  @Override
719  public K firstKey() {
720    return keySet().first();
721  }
722
723  @Override
724  public K lastKey() {
725    return keySet().last();
726  }
727
728  private ImmutableSortedMap<K, V> getSubMap(int fromIndex, int toIndex) {
729    if (fromIndex == 0 && toIndex == size()) {
730      return this;
731    } else if (fromIndex == toIndex) {
732      return emptyMap(comparator());
733    } else {
734      return new ImmutableSortedMap<>(
735          keySet.getSubSet(fromIndex, toIndex), valueList.subList(fromIndex, toIndex));
736    }
737  }
738
739  /**
740   * This method returns a {@code ImmutableSortedMap}, consisting of the entries
741   * whose keys are less than {@code toKey}.
742   *
743   * <p>The {@link SortedMap#headMap} documentation states that a submap of a
744   * submap throws an {@link IllegalArgumentException} if passed a {@code toKey}
745   * greater than an earlier {@code toKey}. However, this method doesn't throw
746   * an exception in that situation, but instead keeps the original {@code
747   * toKey}.
748   */
749  @Override
750  public ImmutableSortedMap<K, V> headMap(K toKey) {
751    return headMap(toKey, false);
752  }
753
754  /**
755   * This method returns a {@code ImmutableSortedMap}, consisting of the entries
756   * whose keys are less than (or equal to, if {@code inclusive}) {@code toKey}.
757   *
758   * <p>The {@link SortedMap#headMap} documentation states that a submap of a
759   * submap throws an {@link IllegalArgumentException} if passed a {@code toKey}
760   * greater than an earlier {@code toKey}. However, this method doesn't throw
761   * an exception in that situation, but instead keeps the original {@code
762   * toKey}.
763   *
764   * @since 12.0
765   */
766  @Override
767  public ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) {
768    return getSubMap(0, keySet.headIndex(checkNotNull(toKey), inclusive));
769  }
770
771  /**
772   * This method returns a {@code ImmutableSortedMap}, consisting of the entries
773   * whose keys ranges from {@code fromKey}, inclusive, to {@code toKey},
774   * exclusive.
775   *
776   * <p>The {@link SortedMap#subMap} documentation states that a submap of a
777   * submap throws an {@link IllegalArgumentException} if passed a {@code
778   * fromKey} less than an earlier {@code fromKey}. However, this method doesn't
779   * throw an exception in that situation, but instead keeps the original {@code
780   * fromKey}. Similarly, this method keeps the original {@code toKey}, instead
781   * of throwing an exception, if passed a {@code toKey} greater than an earlier
782   * {@code toKey}.
783   */
784  @Override
785  public ImmutableSortedMap<K, V> subMap(K fromKey, K toKey) {
786    return subMap(fromKey, true, toKey, false);
787  }
788
789  /**
790   * This method returns a {@code ImmutableSortedMap}, consisting of the entries
791   * whose keys ranges from {@code fromKey} to {@code toKey}, inclusive or
792   * exclusive as indicated by the boolean flags.
793   *
794   * <p>The {@link SortedMap#subMap} documentation states that a submap of a
795   * submap throws an {@link IllegalArgumentException} if passed a {@code
796   * fromKey} less than an earlier {@code fromKey}. However, this method doesn't
797   * throw an exception in that situation, but instead keeps the original {@code
798   * fromKey}. Similarly, this method keeps the original {@code toKey}, instead
799   * of throwing an exception, if passed a {@code toKey} greater than an earlier
800   * {@code toKey}.
801   *
802   * @since 12.0
803   */
804  @Override
805  public ImmutableSortedMap<K, V> subMap(
806      K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
807    checkNotNull(fromKey);
808    checkNotNull(toKey);
809    checkArgument(
810        comparator().compare(fromKey, toKey) <= 0,
811        "expected fromKey <= toKey but %s > %s",
812        fromKey,
813        toKey);
814    return headMap(toKey, toInclusive).tailMap(fromKey, fromInclusive);
815  }
816
817  /**
818   * This method returns a {@code ImmutableSortedMap}, consisting of the entries
819   * whose keys are greater than or equals to {@code fromKey}.
820   *
821   * <p>The {@link SortedMap#tailMap} documentation states that a submap of a
822   * submap throws an {@link IllegalArgumentException} if passed a {@code
823   * fromKey} less than an earlier {@code fromKey}. However, this method doesn't
824   * throw an exception in that situation, but instead keeps the original {@code
825   * fromKey}.
826   */
827  @Override
828  public ImmutableSortedMap<K, V> tailMap(K fromKey) {
829    return tailMap(fromKey, true);
830  }
831
832  /**
833   * This method returns a {@code ImmutableSortedMap}, consisting of the entries
834   * whose keys are greater than (or equal to, if {@code inclusive})
835   * {@code fromKey}.
836   *
837   * <p>The {@link SortedMap#tailMap} documentation states that a submap of a
838   * submap throws an {@link IllegalArgumentException} if passed a {@code
839   * fromKey} less than an earlier {@code fromKey}. However, this method doesn't
840   * throw an exception in that situation, but instead keeps the original {@code
841   * fromKey}.
842   *
843   * @since 12.0
844   */
845  @Override
846  public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) {
847    return getSubMap(keySet.tailIndex(checkNotNull(fromKey), inclusive), size());
848  }
849
850  @Override
851  public Entry<K, V> lowerEntry(K key) {
852    return headMap(key, false).lastEntry();
853  }
854
855  @Override
856  public K lowerKey(K key) {
857    return keyOrNull(lowerEntry(key));
858  }
859
860  @Override
861  public Entry<K, V> floorEntry(K key) {
862    return headMap(key, true).lastEntry();
863  }
864
865  @Override
866  public K floorKey(K key) {
867    return keyOrNull(floorEntry(key));
868  }
869
870  @Override
871  public Entry<K, V> ceilingEntry(K key) {
872    return tailMap(key, true).firstEntry();
873  }
874
875  @Override
876  public K ceilingKey(K key) {
877    return keyOrNull(ceilingEntry(key));
878  }
879
880  @Override
881  public Entry<K, V> higherEntry(K key) {
882    return tailMap(key, false).firstEntry();
883  }
884
885  @Override
886  public K higherKey(K key) {
887    return keyOrNull(higherEntry(key));
888  }
889
890  @Override
891  public Entry<K, V> firstEntry() {
892    return isEmpty() ? null : entrySet().asList().get(0);
893  }
894
895  @Override
896  public Entry<K, V> lastEntry() {
897    return isEmpty() ? null : entrySet().asList().get(size() - 1);
898  }
899
900  /**
901   * Guaranteed to throw an exception and leave the map unmodified.
902   *
903   * @throws UnsupportedOperationException always
904   * @deprecated Unsupported operation.
905   */
906  @CanIgnoreReturnValue
907  @Deprecated
908  @Override
909  public final Entry<K, V> pollFirstEntry() {
910    throw new UnsupportedOperationException();
911  }
912
913  /**
914   * Guaranteed to throw an exception and leave the map unmodified.
915   *
916   * @throws UnsupportedOperationException always
917   * @deprecated Unsupported operation.
918   */
919  @CanIgnoreReturnValue
920  @Deprecated
921  @Override
922  public final Entry<K, V> pollLastEntry() {
923    throw new UnsupportedOperationException();
924  }
925
926  @Override
927  public ImmutableSortedMap<K, V> descendingMap() {
928    // TODO(kevinb): the descendingMap is never actually cached at all. Either it should be or the
929    // code below simplified.
930    ImmutableSortedMap<K, V> result = descendingMap;
931    if (result == null) {
932      if (isEmpty()) {
933        return result = emptyMap(Ordering.from(comparator()).reverse());
934      } else {
935        return result =
936            new ImmutableSortedMap<>(
937                (RegularImmutableSortedSet<K>) keySet.descendingSet(), valueList.reverse(), this);
938      }
939    }
940    return result;
941  }
942
943  @Override
944  public ImmutableSortedSet<K> navigableKeySet() {
945    return keySet;
946  }
947
948  @Override
949  public ImmutableSortedSet<K> descendingKeySet() {
950    return keySet.descendingSet();
951  }
952
953  /**
954   * Serialized type for all ImmutableSortedMap instances. It captures the
955   * logical contents and they are reconstructed using public factory methods.
956   * This ensures that the implementation types remain as implementation
957   * details.
958   */
959  private static class SerializedForm extends ImmutableMap.SerializedForm {
960    private final Comparator<Object> comparator;
961
962    @SuppressWarnings("unchecked")
963    SerializedForm(ImmutableSortedMap<?, ?> sortedMap) {
964      super(sortedMap);
965      comparator = (Comparator<Object>) sortedMap.comparator();
966    }
967
968    @Override
969    Object readResolve() {
970      Builder<Object, Object> builder = new Builder<>(comparator);
971      return createMap(builder);
972    }
973
974    private static final long serialVersionUID = 0;
975  }
976
977  @Override
978  Object writeReplace() {
979    return new SerializedForm(this);
980  }
981
982  // This class is never actually serialized directly, but we have to make the
983  // warning go away (and suppressing would suppress for all nested classes too)
984  private static final long serialVersionUID = 0;
985}