• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.collect;
18 
19 import static com.google.common.base.Preconditions.checkNotNull;
20 
21 import com.google.common.annotations.GwtCompatible;
22 import com.google.common.annotations.GwtIncompatible;
23 import java.io.IOException;
24 import java.io.ObjectInputStream;
25 import java.io.ObjectOutputStream;
26 import java.util.Collection;
27 import java.util.Comparator;
28 import java.util.Map;
29 import java.util.NavigableMap;
30 import java.util.NavigableSet;
31 import java.util.SortedSet;
32 import java.util.TreeMap;
33 import java.util.TreeSet;
34 import org.checkerframework.checker.nullness.compatqual.NullableDecl;
35 
36 /**
37  * Implementation of {@code Multimap} whose keys and values are ordered by their natural ordering or
38  * by supplied comparators. In all cases, this implementation uses {@link Comparable#compareTo} or
39  * {@link Comparator#compare} instead of {@link Object#equals} to determine equivalence of
40  * instances.
41  *
42  * <p><b>Warning:</b> The comparators or comparables used must be <i>consistent with equals</i> as
43  * explained by the {@link Comparable} class specification. Otherwise, the resulting multiset will
44  * violate the general contract of {@link SetMultimap}, which is specified in terms of {@link
45  * Object#equals}.
46  *
47  * <p>The collections returned by {@code keySet} and {@code asMap} iterate through the keys
48  * according to the key comparator ordering or the natural ordering of the keys. Similarly, {@code
49  * get}, {@code removeAll}, and {@code replaceValues} return collections that iterate through the
50  * values according to the value comparator ordering or the natural ordering of the values. The
51  * collections generated by {@code entries}, {@code keys}, and {@code values} iterate across the
52  * keys according to the above key ordering, and for each key they iterate across the values
53  * according to the value ordering.
54  *
55  * <p>The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an
56  * existing key-value pair has no effect.
57  *
58  * <p>Null keys and values are permitted (provided, of course, that the respective comparators
59  * support them). All optional multimap methods are supported, and all returned views are
60  * modifiable.
61  *
62  * <p>This class is not threadsafe when any concurrent operations update the multimap. Concurrent
63  * read operations will work correctly. To allow concurrent update operations, wrap your multimap
64  * with a call to {@link Multimaps#synchronizedSortedSetMultimap}.
65  *
66  * <p>See the Guava User Guide article on <a href=
67  * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap"> {@code
68  * Multimap}</a>.
69  *
70  * @author Jared Levy
71  * @author Louis Wasserman
72  * @since 2.0
73  */
74 @GwtCompatible(serializable = true, emulated = true)
75 public class TreeMultimap<K, V> extends AbstractSortedKeySortedSetMultimap<K, V> {
76   private transient Comparator<? super K> keyComparator;
77   private transient Comparator<? super V> valueComparator;
78 
79   /**
80    * Creates an empty {@code TreeMultimap} ordered by the natural ordering of its keys and values.
81    */
create()82   public static <K extends Comparable, V extends Comparable> TreeMultimap<K, V> create() {
83     return new TreeMultimap<>(Ordering.natural(), Ordering.natural());
84   }
85 
86   /**
87    * Creates an empty {@code TreeMultimap} instance using explicit comparators. Neither comparator
88    * may be null; use {@link Ordering#natural()} to specify natural order.
89    *
90    * @param keyComparator the comparator that determines the key ordering
91    * @param valueComparator the comparator that determines the value ordering
92    */
create( Comparator<? super K> keyComparator, Comparator<? super V> valueComparator)93   public static <K, V> TreeMultimap<K, V> create(
94       Comparator<? super K> keyComparator, Comparator<? super V> valueComparator) {
95     return new TreeMultimap<>(checkNotNull(keyComparator), checkNotNull(valueComparator));
96   }
97 
98   /**
99    * Constructs a {@code TreeMultimap}, ordered by the natural ordering of its keys and values, with
100    * the same mappings as the specified multimap.
101    *
102    * @param multimap the multimap whose contents are copied to this multimap
103    */
create( Multimap<? extends K, ? extends V> multimap)104   public static <K extends Comparable, V extends Comparable> TreeMultimap<K, V> create(
105       Multimap<? extends K, ? extends V> multimap) {
106     return new TreeMultimap<>(Ordering.natural(), Ordering.natural(), multimap);
107   }
108 
TreeMultimap(Comparator<? super K> keyComparator, Comparator<? super V> valueComparator)109   TreeMultimap(Comparator<? super K> keyComparator, Comparator<? super V> valueComparator) {
110     super(new TreeMap<K, Collection<V>>(keyComparator));
111     this.keyComparator = keyComparator;
112     this.valueComparator = valueComparator;
113   }
114 
TreeMultimap( Comparator<? super K> keyComparator, Comparator<? super V> valueComparator, Multimap<? extends K, ? extends V> multimap)115   private TreeMultimap(
116       Comparator<? super K> keyComparator,
117       Comparator<? super V> valueComparator,
118       Multimap<? extends K, ? extends V> multimap) {
119     this(keyComparator, valueComparator);
120     putAll(multimap);
121   }
122 
123   @Override
createAsMap()124   Map<K, Collection<V>> createAsMap() {
125     return createMaybeNavigableAsMap();
126   }
127 
128   /**
129    * {@inheritDoc}
130    *
131    * <p>Creates an empty {@code TreeSet} for a collection of values for one key.
132    *
133    * @return a new {@code TreeSet} containing a collection of values for one key
134    */
135   @Override
createCollection()136   SortedSet<V> createCollection() {
137     return new TreeSet<V>(valueComparator);
138   }
139 
140   @Override
createCollection(@ullableDecl K key)141   Collection<V> createCollection(@NullableDecl K key) {
142     if (key == null) {
143       keyComparator().compare(key, key);
144     }
145     return super.createCollection(key);
146   }
147 
148   /**
149    * Returns the comparator that orders the multimap keys.
150    *
151    * @deprecated Use {@code ((NavigableSet<K>) multimap.keySet()).comparator()} instead.
152    */
153   @Deprecated
keyComparator()154   public Comparator<? super K> keyComparator() {
155     return keyComparator;
156   }
157 
158   @Override
valueComparator()159   public Comparator<? super V> valueComparator() {
160     return valueComparator;
161   }
162 
163   /** @since 14.0 (present with return type {@code SortedSet} since 2.0) */
164   @Override
165   @GwtIncompatible // NavigableSet
get(@ullableDecl K key)166   public NavigableSet<V> get(@NullableDecl K key) {
167     return (NavigableSet<V>) super.get(key);
168   }
169 
170   /**
171    * {@inheritDoc}
172    *
173    * <p>Because a {@code TreeMultimap} has unique sorted keys, this method returns a {@link
174    * NavigableSet}, instead of the {@link java.util.Set} specified in the {@link Multimap}
175    * interface.
176    *
177    * @since 14.0 (present with return type {@code SortedSet} since 2.0)
178    */
179   @Override
keySet()180   public NavigableSet<K> keySet() {
181     return (NavigableSet<K>) super.keySet();
182   }
183 
184   /**
185    * {@inheritDoc}
186    *
187    * <p>Because a {@code TreeMultimap} has unique sorted keys, this method returns a {@link
188    * NavigableMap}, instead of the {@link java.util.Map} specified in the {@link Multimap}
189    * interface.
190    *
191    * @since 14.0 (present with return type {@code SortedMap} since 2.0)
192    */
193   @Override
asMap()194   public NavigableMap<K, Collection<V>> asMap() {
195     return (NavigableMap<K, Collection<V>>) super.asMap();
196   }
197 
198   /**
199    * @serialData key comparator, value comparator, number of distinct keys, and then for each
200    *     distinct key: the key, number of values for that key, and key values
201    */
202   @GwtIncompatible // java.io.ObjectOutputStream
writeObject(ObjectOutputStream stream)203   private void writeObject(ObjectOutputStream stream) throws IOException {
204     stream.defaultWriteObject();
205     stream.writeObject(keyComparator());
206     stream.writeObject(valueComparator());
207     Serialization.writeMultimap(this, stream);
208   }
209 
210   @GwtIncompatible // java.io.ObjectInputStream
211   @SuppressWarnings("unchecked") // reading data stored by writeObject
readObject(ObjectInputStream stream)212   private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
213     stream.defaultReadObject();
214     keyComparator = checkNotNull((Comparator<? super K>) stream.readObject());
215     valueComparator = checkNotNull((Comparator<? super V>) stream.readObject());
216     setMap(new TreeMap<K, Collection<V>>(keyComparator));
217     Serialization.populateMultimap(this, stream);
218   }
219 
220   @GwtIncompatible // not needed in emulated source
221   private static final long serialVersionUID = 0;
222 }
223