001/*
002 * Copyright (C) 2012 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.base.Predicates.compose;
022import static com.google.common.base.Predicates.in;
023import static com.google.common.base.Predicates.not;
024import static java.util.Objects.requireNonNull;
025
026import com.google.common.annotations.GwtIncompatible;
027import com.google.common.base.MoreObjects;
028import com.google.common.base.Predicate;
029import com.google.common.collect.Maps.IteratorBasedAbstractMap;
030import java.util.AbstractMap;
031import java.util.Collection;
032import java.util.Collections;
033import java.util.Iterator;
034import java.util.List;
035import java.util.Map;
036import java.util.Map.Entry;
037import java.util.NavigableMap;
038import java.util.NoSuchElementException;
039import java.util.Set;
040import java.util.function.BiFunction;
041import javax.annotation.CheckForNull;
042import org.checkerframework.checker.nullness.qual.Nullable;
043
044/**
045 * An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
046 * operations.
047 *
048 * <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
049 *
050 * @author Louis Wasserman
051 * @since 14.0
052 */
053@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
054@GwtIncompatible // NavigableMap
055@ElementTypesAreNonnullByDefault
056public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
057
058  private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
059
060  public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
061    return new TreeRangeMap<>();
062  }
063
064  private TreeRangeMap() {
065    this.entriesByLowerBound = Maps.newTreeMap();
066  }
067
068  private static final class RangeMapEntry<K extends Comparable, V>
069      extends AbstractMapEntry<Range<K>, V> {
070    private final Range<K> range;
071    private final V value;
072
073    RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
074      this(Range.create(lowerBound, upperBound), value);
075    }
076
077    RangeMapEntry(Range<K> range, V value) {
078      this.range = range;
079      this.value = value;
080    }
081
082    @Override
083    public Range<K> getKey() {
084      return range;
085    }
086
087    @Override
088    public V getValue() {
089      return value;
090    }
091
092    public boolean contains(K value) {
093      return range.contains(value);
094    }
095
096    Cut<K> getLowerBound() {
097      return range.lowerBound;
098    }
099
100    Cut<K> getUpperBound() {
101      return range.upperBound;
102    }
103  }
104
105  @Override
106  @CheckForNull
107  public V get(K key) {
108    Entry<Range<K>, V> entry = getEntry(key);
109    return (entry == null) ? null : entry.getValue();
110  }
111
112  @Override
113  @CheckForNull
114  public Entry<Range<K>, V> getEntry(K key) {
115    Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
116        entriesByLowerBound.floorEntry(Cut.belowValue(key));
117    if (mapEntry != null && mapEntry.getValue().contains(key)) {
118      return mapEntry.getValue();
119    } else {
120      return null;
121    }
122  }
123
124  @Override
125  public void put(Range<K> range, V value) {
126    if (!range.isEmpty()) {
127      checkNotNull(value);
128      remove(range);
129      entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
130    }
131  }
132
133  @Override
134  public void putCoalescing(Range<K> range, V value) {
135    // don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
136    if (entriesByLowerBound.isEmpty()) {
137      put(range, value);
138      return;
139    }
140
141    Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
142    put(coalescedRange, value);
143  }
144
145  /** Computes the coalesced range for the given range+value - does not mutate the map. */
146  private Range<K> coalescedRange(Range<K> range, V value) {
147    Range<K> coalescedRange = range;
148    Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
149        entriesByLowerBound.lowerEntry(range.lowerBound);
150    coalescedRange = coalesce(coalescedRange, value, lowerEntry);
151
152    Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
153        entriesByLowerBound.floorEntry(range.upperBound);
154    coalescedRange = coalesce(coalescedRange, value, higherEntry);
155
156    return coalescedRange;
157  }
158
159  /** Returns the range that spans the given range and entry, if the entry can be coalesced. */
160  private static <K extends Comparable, V> Range<K> coalesce(
161      Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
162    if (entry != null
163        && entry.getValue().getKey().isConnected(range)
164        && entry.getValue().getValue().equals(value)) {
165      return range.span(entry.getValue().getKey());
166    }
167    return range;
168  }
169
170  @Override
171  public void putAll(RangeMap<K, ? extends V> rangeMap) {
172    for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
173      put(entry.getKey(), entry.getValue());
174    }
175  }
176
177  @Override
178  public void clear() {
179    entriesByLowerBound.clear();
180  }
181
182  @Override
183  public Range<K> span() {
184    Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
185    Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
186    // Either both are null or neither is, but we check both to satisfy the nullness checker.
187    if (firstEntry == null || lastEntry == null) {
188      throw new NoSuchElementException();
189    }
190    return Range.create(
191        firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
192  }
193
194  private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
195    entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
196  }
197
198  @Override
199  public void remove(Range<K> rangeToRemove) {
200    if (rangeToRemove.isEmpty()) {
201      return;
202    }
203
204    /*
205     * The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
206     * indicate the bounds of ranges in the range map.
207     */
208    Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
209        entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
210    if (mapEntryBelowToTruncate != null) {
211      // we know ( [
212      RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
213      if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
214        // we know ( [ )
215        if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
216          // we know ( [ ] ), so insert the range ] ) back into the map --
217          // it's being split apart
218          putRangeMapEntry(
219              rangeToRemove.upperBound,
220              rangeMapEntry.getUpperBound(),
221              mapEntryBelowToTruncate.getValue().getValue());
222        }
223        // overwrite mapEntryToTruncateBelow with a truncated range
224        putRangeMapEntry(
225            rangeMapEntry.getLowerBound(),
226            rangeToRemove.lowerBound,
227            mapEntryBelowToTruncate.getValue().getValue());
228      }
229    }
230
231    Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
232        entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
233    if (mapEntryAboveToTruncate != null) {
234      // we know ( ]
235      RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
236      if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
237        // we know ( ] ), and since we dealt with truncating below already,
238        // we know [ ( ] )
239        putRangeMapEntry(
240            rangeToRemove.upperBound,
241            rangeMapEntry.getUpperBound(),
242            mapEntryAboveToTruncate.getValue().getValue());
243      }
244    }
245    entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
246  }
247
248  private void split(Cut<K> cut) {
249    /*
250     * The comments for this method will use | to indicate the cut point and ( ) to indicate the
251     * bounds of ranges in the range map.
252     */
253    Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
254    if (mapEntryToSplit == null) {
255      return;
256    }
257    // we know ( |
258    RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
259    if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
260      return;
261    }
262    // we know ( | )
263    putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
264    putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
265  }
266
267  @Override
268  public void merge(
269      Range<K> range,
270      @CheckForNull V value,
271      BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
272    checkNotNull(range);
273    checkNotNull(remappingFunction);
274
275    if (range.isEmpty()) {
276      return;
277    }
278    split(range.lowerBound);
279    split(range.upperBound);
280
281    // Due to the splitting of any entries spanning the range bounds, we know that any entry with a
282    // lower bound in the merge range is entirely contained by the merge range.
283    Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
284        entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
285
286    // Create entries mapping any unmapped ranges in the merge range to the specified value.
287    ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
288    if (value != null) {
289      final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
290          entriesInMergeRange.iterator();
291      Cut<K> lowerBound = range.lowerBound;
292      while (backingItr.hasNext()) {
293        RangeMapEntry<K, V> entry = backingItr.next().getValue();
294        Cut<K> upperBound = entry.getLowerBound();
295        if (!lowerBound.equals(upperBound)) {
296          gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
297        }
298        lowerBound = entry.getUpperBound();
299      }
300      if (!lowerBound.equals(range.upperBound)) {
301        gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
302      }
303    }
304
305    // Remap all existing entries in the merge range.
306    final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
307    while (backingItr.hasNext()) {
308      Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
309      V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
310      if (newValue == null) {
311        backingItr.remove();
312      } else {
313        entry.setValue(
314            new RangeMapEntry<K, V>(
315                entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
316      }
317    }
318
319    entriesByLowerBound.putAll(gaps.build());
320  }
321
322  @Override
323  public Map<Range<K>, V> asMapOfRanges() {
324    return new AsMapOfRanges(entriesByLowerBound.values());
325  }
326
327  @Override
328  public Map<Range<K>, V> asDescendingMapOfRanges() {
329    return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
330  }
331
332  private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
333
334    final Iterable<Entry<Range<K>, V>> entryIterable;
335
336    @SuppressWarnings("unchecked") // it's safe to upcast iterables
337    AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
338      this.entryIterable = (Iterable) entryIterable;
339    }
340
341    @Override
342    public boolean containsKey(@CheckForNull Object key) {
343      return get(key) != null;
344    }
345
346    @Override
347    @CheckForNull
348    public V get(@CheckForNull Object key) {
349      if (key instanceof Range) {
350        Range<?> range = (Range<?>) key;
351        RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
352        if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
353          return rangeMapEntry.getValue();
354        }
355      }
356      return null;
357    }
358
359    @Override
360    public int size() {
361      return entriesByLowerBound.size();
362    }
363
364    @Override
365    Iterator<Entry<Range<K>, V>> entryIterator() {
366      return entryIterable.iterator();
367    }
368  }
369
370  @Override
371  public RangeMap<K, V> subRangeMap(Range<K> subRange) {
372    if (subRange.equals(Range.all())) {
373      return this;
374    } else {
375      return new SubRangeMap(subRange);
376    }
377  }
378
379  @SuppressWarnings("unchecked")
380  private RangeMap<K, V> emptySubRangeMap() {
381    return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
382  }
383
384  @SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
385  private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
386      new RangeMap<Comparable<?>, Object>() {
387        @Override
388        @CheckForNull
389        public Object get(Comparable<?> key) {
390          return null;
391        }
392
393        @Override
394        @CheckForNull
395        public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
396          return null;
397        }
398
399        @Override
400        public Range<Comparable<?>> span() {
401          throw new NoSuchElementException();
402        }
403
404        @Override
405        public void put(Range<Comparable<?>> range, Object value) {
406          checkNotNull(range);
407          throw new IllegalArgumentException(
408              "Cannot insert range " + range + " into an empty subRangeMap");
409        }
410
411        @Override
412        public void putCoalescing(Range<Comparable<?>> range, Object value) {
413          checkNotNull(range);
414          throw new IllegalArgumentException(
415              "Cannot insert range " + range + " into an empty subRangeMap");
416        }
417
418        @Override
419        public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
420          if (!rangeMap.asMapOfRanges().isEmpty()) {
421            throw new IllegalArgumentException(
422                "Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
423          }
424        }
425
426        @Override
427        public void clear() {}
428
429        @Override
430        public void remove(Range<Comparable<?>> range) {
431          checkNotNull(range);
432        }
433
434        @Override
435        // https://github.com/jspecify/jspecify-reference-checker/issues/162
436        @SuppressWarnings("nullness")
437        public void merge(
438            Range<Comparable<?>> range,
439            @CheckForNull Object value,
440            BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
441                remappingFunction) {
442          checkNotNull(range);
443          throw new IllegalArgumentException(
444              "Cannot merge range " + range + " into an empty subRangeMap");
445        }
446
447        @Override
448        public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
449          return Collections.emptyMap();
450        }
451
452        @Override
453        public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
454          return Collections.emptyMap();
455        }
456
457        @Override
458        public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
459          checkNotNull(range);
460          return this;
461        }
462      };
463
464  private class SubRangeMap implements RangeMap<K, V> {
465
466    private final Range<K> subRange;
467
468    SubRangeMap(Range<K> subRange) {
469      this.subRange = subRange;
470    }
471
472    @Override
473    @CheckForNull
474    public V get(K key) {
475      return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
476    }
477
478    @Override
479    @CheckForNull
480    public Entry<Range<K>, V> getEntry(K key) {
481      if (subRange.contains(key)) {
482        Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
483        if (entry != null) {
484          return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
485        }
486      }
487      return null;
488    }
489
490    @Override
491    public Range<K> span() {
492      Cut<K> lowerBound;
493      Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
494          entriesByLowerBound.floorEntry(subRange.lowerBound);
495      if (lowerEntry != null
496          && lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
497        lowerBound = subRange.lowerBound;
498      } else {
499        lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
500        if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
501          throw new NoSuchElementException();
502        }
503      }
504
505      Cut<K> upperBound;
506      Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
507          entriesByLowerBound.lowerEntry(subRange.upperBound);
508      if (upperEntry == null) {
509        throw new NoSuchElementException();
510      } else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
511        upperBound = subRange.upperBound;
512      } else {
513        upperBound = upperEntry.getValue().getUpperBound();
514      }
515      return Range.create(lowerBound, upperBound);
516    }
517
518    @Override
519    public void put(Range<K> range, V value) {
520      checkArgument(
521          subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
522      TreeRangeMap.this.put(range, value);
523    }
524
525    @Override
526    public void putCoalescing(Range<K> range, V value) {
527      if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
528        put(range, value);
529        return;
530      }
531
532      Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
533      // only coalesce ranges within the subRange
534      put(coalescedRange.intersection(subRange), value);
535    }
536
537    @Override
538    public void putAll(RangeMap<K, ? extends V> rangeMap) {
539      if (rangeMap.asMapOfRanges().isEmpty()) {
540        return;
541      }
542      Range<K> span = rangeMap.span();
543      checkArgument(
544          subRange.encloses(span),
545          "Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
546          span,
547          subRange);
548      TreeRangeMap.this.putAll(rangeMap);
549    }
550
551    @Override
552    public void clear() {
553      TreeRangeMap.this.remove(subRange);
554    }
555
556    @Override
557    public void remove(Range<K> range) {
558      if (range.isConnected(subRange)) {
559        TreeRangeMap.this.remove(range.intersection(subRange));
560      }
561    }
562
563    @Override
564    public void merge(
565        Range<K> range,
566        @CheckForNull V value,
567        BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
568      checkArgument(
569          subRange.encloses(range),
570          "Cannot merge range %s into a subRangeMap(%s)",
571          range,
572          subRange);
573      TreeRangeMap.this.merge(range, value, remappingFunction);
574    }
575
576    @Override
577    public RangeMap<K, V> subRangeMap(Range<K> range) {
578      if (!range.isConnected(subRange)) {
579        return emptySubRangeMap();
580      } else {
581        return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
582      }
583    }
584
585    @Override
586    public Map<Range<K>, V> asMapOfRanges() {
587      return new SubRangeMapAsMap();
588    }
589
590    @Override
591    public Map<Range<K>, V> asDescendingMapOfRanges() {
592      return new SubRangeMapAsMap() {
593
594        @Override
595        Iterator<Entry<Range<K>, V>> entryIterator() {
596          if (subRange.isEmpty()) {
597            return Iterators.emptyIterator();
598          }
599          final Iterator<RangeMapEntry<K, V>> backingItr =
600              entriesByLowerBound
601                  .headMap(subRange.upperBound, false)
602                  .descendingMap()
603                  .values()
604                  .iterator();
605          return new AbstractIterator<Entry<Range<K>, V>>() {
606
607            @Override
608            @CheckForNull
609            protected Entry<Range<K>, V> computeNext() {
610              if (backingItr.hasNext()) {
611                RangeMapEntry<K, V> entry = backingItr.next();
612                if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
613                  return endOfData();
614                }
615                return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
616              }
617              return endOfData();
618            }
619          };
620        }
621      };
622    }
623
624    @Override
625    public boolean equals(@CheckForNull Object o) {
626      if (o instanceof RangeMap) {
627        RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
628        return asMapOfRanges().equals(rangeMap.asMapOfRanges());
629      }
630      return false;
631    }
632
633    @Override
634    public int hashCode() {
635      return asMapOfRanges().hashCode();
636    }
637
638    @Override
639    public String toString() {
640      return asMapOfRanges().toString();
641    }
642
643    class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
644
645      @Override
646      public boolean containsKey(@CheckForNull Object key) {
647        return get(key) != null;
648      }
649
650      @Override
651      @CheckForNull
652      public V get(@CheckForNull Object key) {
653        try {
654          if (key instanceof Range) {
655            @SuppressWarnings("unchecked") // we catch ClassCastExceptions
656            Range<K> r = (Range<K>) key;
657            if (!subRange.encloses(r) || r.isEmpty()) {
658              return null;
659            }
660            RangeMapEntry<K, V> candidate = null;
661            if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
662              // r could be truncated on the left
663              Entry<Cut<K>, RangeMapEntry<K, V>> entry =
664                  entriesByLowerBound.floorEntry(r.lowerBound);
665              if (entry != null) {
666                candidate = entry.getValue();
667              }
668            } else {
669              candidate = entriesByLowerBound.get(r.lowerBound);
670            }
671
672            if (candidate != null
673                && candidate.getKey().isConnected(subRange)
674                && candidate.getKey().intersection(subRange).equals(r)) {
675              return candidate.getValue();
676            }
677          }
678        } catch (ClassCastException e) {
679          return null;
680        }
681        return null;
682      }
683
684      @Override
685      @CheckForNull
686      public V remove(@CheckForNull Object key) {
687        V value = get(key);
688        if (value != null) {
689          // it's definitely in the map, so the cast and requireNonNull are safe
690          @SuppressWarnings("unchecked")
691          Range<K> range = (Range<K>) requireNonNull(key);
692          TreeRangeMap.this.remove(range);
693          return value;
694        }
695        return null;
696      }
697
698      @Override
699      public void clear() {
700        SubRangeMap.this.clear();
701      }
702
703      private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
704        List<Range<K>> toRemove = Lists.newArrayList();
705        for (Entry<Range<K>, V> entry : entrySet()) {
706          if (predicate.apply(entry)) {
707            toRemove.add(entry.getKey());
708          }
709        }
710        for (Range<K> range : toRemove) {
711          TreeRangeMap.this.remove(range);
712        }
713        return !toRemove.isEmpty();
714      }
715
716      @Override
717      public Set<Range<K>> keySet() {
718        return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
719          @Override
720          public boolean remove(@CheckForNull Object o) {
721            return SubRangeMapAsMap.this.remove(o) != null;
722          }
723
724          @Override
725          public boolean retainAll(Collection<?> c) {
726            return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
727          }
728        };
729      }
730
731      @Override
732      public Set<Entry<Range<K>, V>> entrySet() {
733        return new Maps.EntrySet<Range<K>, V>() {
734          @Override
735          Map<Range<K>, V> map() {
736            return SubRangeMapAsMap.this;
737          }
738
739          @Override
740          public Iterator<Entry<Range<K>, V>> iterator() {
741            return entryIterator();
742          }
743
744          @Override
745          public boolean retainAll(Collection<?> c) {
746            return removeEntryIf(not(in(c)));
747          }
748
749          @Override
750          public int size() {
751            return Iterators.size(iterator());
752          }
753
754          @Override
755          public boolean isEmpty() {
756            return !iterator().hasNext();
757          }
758        };
759      }
760
761      Iterator<Entry<Range<K>, V>> entryIterator() {
762        if (subRange.isEmpty()) {
763          return Iterators.emptyIterator();
764        }
765        Cut<K> cutToStart =
766            MoreObjects.firstNonNull(
767                entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
768        final Iterator<RangeMapEntry<K, V>> backingItr =
769            entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
770        return new AbstractIterator<Entry<Range<K>, V>>() {
771
772          @Override
773          @CheckForNull
774          protected Entry<Range<K>, V> computeNext() {
775            while (backingItr.hasNext()) {
776              RangeMapEntry<K, V> entry = backingItr.next();
777              if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
778                return endOfData();
779              } else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
780                // this might not be true e.g. at the start of the iteration
781                return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
782              }
783            }
784            return endOfData();
785          }
786        };
787      }
788
789      @Override
790      public Collection<V> values() {
791        return new Maps.Values<Range<K>, V>(this) {
792          @Override
793          public boolean removeAll(Collection<?> c) {
794            return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
795          }
796
797          @Override
798          public boolean retainAll(Collection<?> c) {
799            return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
800          }
801        };
802      }
803    }
804  }
805
806  @Override
807  public boolean equals(@CheckForNull Object o) {
808    if (o instanceof RangeMap) {
809      RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
810      return asMapOfRanges().equals(rangeMap.asMapOfRanges());
811    }
812    return false;
813  }
814
815  @Override
816  public int hashCode() {
817    return asMapOfRanges().hashCode();
818  }
819
820  @Override
821  public String toString() {
822    return entriesByLowerBound.values().toString();
823  }
824}