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    
017    package com.google.common.collect;
018    
019    import static com.google.common.base.Preconditions.checkNotNull;
020    
021    import com.google.common.annotations.Beta;
022    import com.google.common.annotations.GwtCompatible;
023    import com.google.common.annotations.GwtIncompatible;
024    import com.google.common.base.Function;
025    
026    import java.io.IOException;
027    import java.io.InvalidObjectException;
028    import java.io.ObjectInputStream;
029    import java.io.ObjectOutputStream;
030    import java.util.Arrays;
031    import java.util.Collection;
032    import java.util.Collections;
033    import java.util.Comparator;
034    import java.util.LinkedHashMap;
035    import java.util.List;
036    import java.util.Map;
037    import java.util.Map.Entry;
038    import java.util.TreeMap;
039    
040    import javax.annotation.Nullable;
041    
042    /**
043     * An immutable {@link SetMultimap} with reliable user-specified key and value
044     * iteration order. Does not permit null keys or values.
045     *
046     * <p>Unlike {@link Multimaps#unmodifiableSetMultimap(SetMultimap)}, which is
047     * a <i>view</i> of a separate multimap which can still change, an instance of
048     * {@code ImmutableSetMultimap} contains its own data and will <i>never</i>
049     * change. {@code ImmutableSetMultimap} is convenient for
050     * {@code public static final} multimaps ("constant multimaps") and also lets
051     * you easily make a "defensive copy" of a multimap provided to your class by
052     * a caller.
053     *
054     * <p><b>Note:</b> Although this class is not final, it cannot be subclassed as
055     * it has no public or protected constructors. Thus, instances of this class
056     * are guaranteed to be immutable.
057     *
058     * <p>See the Guava User Guide article on <a href=
059     * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
060     * immutable collections</a>.
061     *
062     * @author Mike Ward
063     * @since 2.0 (imported from Google Collections Library)
064     */
065    @GwtCompatible(serializable = true, emulated = true)
066    public class ImmutableSetMultimap<K, V>
067        extends ImmutableMultimap<K, V>
068        implements SetMultimap<K, V> {
069    
070      /** Returns the empty multimap. */
071      // Casting is safe because the multimap will never hold any elements.
072      @SuppressWarnings("unchecked")
073      public static <K, V> ImmutableSetMultimap<K, V> of() {
074        return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
075      }
076    
077      /**
078       * Returns an immutable multimap containing a single entry.
079       */
080      public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) {
081        ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
082        builder.put(k1, v1);
083        return builder.build();
084      }
085    
086      /**
087       * Returns an immutable multimap containing the given entries, in order.
088       * Repeated occurrences of an entry (according to {@link Object#equals}) after
089       * the first are ignored.
090       */
091      public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) {
092        ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
093        builder.put(k1, v1);
094        builder.put(k2, v2);
095        return builder.build();
096      }
097    
098      /**
099       * Returns an immutable multimap containing the given entries, in order.
100       * Repeated occurrences of an entry (according to {@link Object#equals}) after
101       * the first are ignored.
102       */
103      public static <K, V> ImmutableSetMultimap<K, V> of(
104          K k1, V v1, K k2, V v2, K k3, V v3) {
105        ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
106        builder.put(k1, v1);
107        builder.put(k2, v2);
108        builder.put(k3, v3);
109        return builder.build();
110      }
111    
112      /**
113       * Returns an immutable multimap containing the given entries, in order.
114       * Repeated occurrences of an entry (according to {@link Object#equals}) after
115       * the first are ignored.
116       */
117      public static <K, V> ImmutableSetMultimap<K, V> of(
118          K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
119        ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
120        builder.put(k1, v1);
121        builder.put(k2, v2);
122        builder.put(k3, v3);
123        builder.put(k4, v4);
124        return builder.build();
125      }
126    
127      /**
128       * Returns an immutable multimap containing the given entries, in order.
129       * Repeated occurrences of an entry (according to {@link Object#equals}) after
130       * the first are ignored.
131       */
132      public static <K, V> ImmutableSetMultimap<K, V> of(
133          K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
134        ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
135        builder.put(k1, v1);
136        builder.put(k2, v2);
137        builder.put(k3, v3);
138        builder.put(k4, v4);
139        builder.put(k5, v5);
140        return builder.build();
141      }
142    
143      // looking for of() with > 5 entries? Use the builder instead.
144    
145      /**
146       * Returns a new {@link Builder}.
147       */
148      public static <K, V> Builder<K, V> builder() {
149        return new Builder<K, V>();
150      }
151    
152      /**
153       * Multimap for {@link ImmutableSetMultimap.Builder} that maintains key
154       * and value orderings and performs better than {@link LinkedHashMultimap}.
155       */
156      private static class BuilderMultimap<K, V> extends AbstractMultimap<K, V> {
157        BuilderMultimap() {
158          super(new LinkedHashMap<K, Collection<V>>());
159        }
160        
161        @Override
162        Collection<V> createCollection() {
163          return Sets.newLinkedHashSet();
164        }
165        private static final long serialVersionUID = 0;
166      }
167    
168      /**
169       * Multimap for {@link ImmutableSetMultimap.Builder} that sorts keys and
170       * maintains value orderings.
171       */
172      private static class SortedKeyBuilderMultimap<K, V>
173          extends AbstractMultimap<K, V> {
174        SortedKeyBuilderMultimap(
175            Comparator<? super K> keyComparator, Multimap<K, V> multimap) {
176          super(new TreeMap<K, Collection<V>>(keyComparator));
177          putAll(multimap);
178        }
179        
180        @Override
181        Collection<V> createCollection() {
182          return Sets.newLinkedHashSet();
183        }
184        private static final long serialVersionUID = 0;
185      }
186    
187      /**
188       * A builder for creating immutable {@code SetMultimap} instances, especially
189       * {@code public static final} multimaps ("constant multimaps"). Example:
190       * <pre>   {@code
191       *
192       *   static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
193       *       new ImmutableSetMultimap.Builder<String, Integer>()
194       *           .put("one", 1)
195       *           .putAll("several", 1, 2, 3)
196       *           .putAll("many", 1, 2, 3, 4, 5)
197       *           .build();}</pre>
198       *
199       * Builder instances can be reused; it is safe to call {@link #build} multiple
200       * times to build multiple multimaps in series. Each multimap contains the
201       * key-value mappings in the previously created multimaps.
202       *
203       * @since 2.0 (imported from Google Collections Library)
204       */
205      public static final class Builder<K, V>
206          extends ImmutableMultimap.Builder<K, V> {
207        /**
208         * Creates a new builder. The returned builder is equivalent to the builder
209         * generated by {@link ImmutableSetMultimap#builder}.
210         */
211        public Builder() {
212          builderMultimap = new BuilderMultimap<K, V>();
213        }
214    
215        /**
216         * Adds a key-value mapping to the built multimap if it is not already
217         * present.
218         */
219        
220        @Override
221        public Builder<K, V> put(K key, V value) {
222          builderMultimap.put(checkNotNull(key), checkNotNull(value));
223          return this;
224        }
225    
226        /**
227         * Adds an entry to the built multimap if it is not already present.
228         *
229         * @since 11.0
230         */
231        
232        @Override
233        public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
234          builderMultimap.put(
235              checkNotNull(entry.getKey()), checkNotNull(entry.getValue()));
236          return this;
237        }
238    
239        
240        @Override
241        public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
242          Collection<V> collection = builderMultimap.get(checkNotNull(key));
243          for (V value : values) {
244            collection.add(checkNotNull(value));
245          }
246          return this;
247        }
248    
249        
250        @Override
251        public Builder<K, V> putAll(K key, V... values) {
252          return putAll(key, Arrays.asList(values));
253        }
254    
255        
256        @Override
257        public Builder<K, V> putAll(
258            Multimap<? extends K, ? extends V> multimap) {
259          for (Entry<? extends K, ? extends Collection<? extends V>> entry
260              : multimap.asMap().entrySet()) {
261            putAll(entry.getKey(), entry.getValue());
262          }
263          return this;
264        }
265    
266        /**
267         * {@inheritDoc}
268         *
269         * @since 8.0
270         */
271        @Beta @Override
272        public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
273          this.keyComparator = checkNotNull(keyComparator);
274          return this;
275        }
276    
277        /**
278         * Specifies the ordering of the generated multimap's values for each key.
279         *
280         * <p>If this method is called, the sets returned by the {@code get()}
281         * method of the generated multimap and its {@link Multimap#asMap()} view
282         * are {@link ImmutableSortedSet} instances. However, serialization does not
283         * preserve that property, though it does maintain the key and value
284         * ordering.
285         *
286         * @since 8.0
287         */
288        // TODO: Make serialization behavior consistent.
289        @Beta @Override
290        public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
291          super.orderValuesBy(valueComparator);
292          return this;
293        }
294    
295        /**
296         * Returns a newly-created immutable set multimap.
297         */
298        
299        @Override
300        public ImmutableSetMultimap<K, V> build() {
301          if (keyComparator != null) {
302            Multimap<K, V> sortedCopy = new BuilderMultimap<K, V>();
303            List<Map.Entry<K, Collection<V>>> entries = Lists.newArrayList(
304                builderMultimap.asMap().entrySet());
305            Collections.sort(
306                entries,
307                Ordering.from(keyComparator).onResultOf(new Function<Entry<K, Collection<V>>, K>() {
308                  public K apply(Entry<K, Collection<V>> entry) {
309                    return entry.getKey();
310                  }
311                }));
312            for (Map.Entry<K, Collection<V>> entry : entries) {
313              sortedCopy.putAll(entry.getKey(), entry.getValue());
314            }
315            builderMultimap = sortedCopy;
316          }
317          return copyOf(builderMultimap, valueComparator);
318        }
319      }
320    
321      /**
322       * Returns an immutable set multimap containing the same mappings as
323       * {@code multimap}. The generated multimap's key and value orderings
324       * correspond to the iteration ordering of the {@code multimap.asMap()} view.
325       * Repeated occurrences of an entry in the multimap after the first are
326       * ignored.
327       *
328       * <p>Despite the method name, this method attempts to avoid actually copying
329       * the data when it is safe to do so. The exact circumstances under which a
330       * copy will or will not be performed are undocumented and subject to change.
331       *
332       * @throws NullPointerException if any key or value in {@code multimap} is
333       *     null
334       */
335      public static <K, V> ImmutableSetMultimap<K, V> copyOf(
336          Multimap<? extends K, ? extends V> multimap) {
337        return copyOf(multimap, null);
338      }
339    
340      private static <K, V> ImmutableSetMultimap<K, V> copyOf(
341          Multimap<? extends K, ? extends V> multimap,
342          Comparator<? super V> valueComparator) {
343        checkNotNull(multimap); // eager for GWT
344        if (multimap.isEmpty() && valueComparator == null) {
345          return of();
346        }
347    
348        if (multimap instanceof ImmutableSetMultimap) {
349          @SuppressWarnings("unchecked") // safe since multimap is not writable
350          ImmutableSetMultimap<K, V> kvMultimap
351              = (ImmutableSetMultimap<K, V>) multimap;
352          if (!kvMultimap.isPartialView()) {
353            return kvMultimap;
354          }
355        }
356    
357        ImmutableMap.Builder<K, ImmutableSet<V>> builder = ImmutableMap.builder();
358        int size = 0;
359    
360        for (Entry<? extends K, ? extends Collection<? extends V>> entry
361            : multimap.asMap().entrySet()) {
362          K key = entry.getKey();
363          Collection<? extends V> values = entry.getValue();
364          ImmutableSet<V> set = (valueComparator == null)
365              ? ImmutableSet.copyOf(values)
366              : ImmutableSortedSet.copyOf(valueComparator, values);
367          if (!set.isEmpty()) {
368            builder.put(key, set);
369            size += set.size();
370          }
371        }
372    
373        return new ImmutableSetMultimap<K, V>(
374            builder.build(), size, valueComparator);
375      }
376    
377      // Returned by get() when values are sorted and a missing key is provided.
378      private final transient ImmutableSortedSet<V> emptySet;
379    
380      ImmutableSetMultimap(ImmutableMap<K, ImmutableSet<V>> map, int size,
381          @Nullable Comparator<? super V> valueComparator) {
382        super(map, size);
383        this.emptySet = (valueComparator == null)
384            ? null : ImmutableSortedSet.<V>emptySet(valueComparator);
385      }
386    
387      // views
388    
389      /**
390       * Returns an immutable set of the values for the given key.  If no mappings
391       * in the multimap have the provided key, an empty immutable set is returned.
392       * The values are in the same order as the parameters used to build this
393       * multimap.
394       */
395      
396      @Override
397      public ImmutableSet<V> get(@Nullable K key) {
398        // This cast is safe as its type is known in constructor.
399        ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
400        if (set != null) {
401          return set;
402        } else if (emptySet != null) {
403          return emptySet;
404        } else {
405          return ImmutableSet.<V>of();
406        }
407      }
408    
409      private transient ImmutableSetMultimap<V, K> inverse;
410    
411      /**
412       * {@inheritDoc}
413       *
414       * <p>Because an inverse of a set multimap cannot contain multiple pairs with
415       * the same key and value, this method returns an {@code ImmutableSetMultimap}
416       * rather than the {@code ImmutableMultimap} specified in the {@code
417       * ImmutableMultimap} class.
418       *
419       * @since 11.0
420       */
421      
422      @Override
423      @Beta
424      public ImmutableSetMultimap<V, K> inverse() {
425        ImmutableSetMultimap<V, K> result = inverse;
426        return (result == null) ? (inverse = invert()) : result;
427      }
428    
429      private ImmutableSetMultimap<V, K> invert() {
430        Builder<V, K> builder = builder();
431        for (Entry<K, V> entry : entries()) {
432          builder.put(entry.getValue(), entry.getKey());
433        }
434        ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
435        invertedMultimap.inverse = this;
436        return invertedMultimap;
437      }
438    
439      /**
440       * Guaranteed to throw an exception and leave the multimap unmodified.
441       *
442       * @throws UnsupportedOperationException always
443       */
444      
445      @Override
446      public ImmutableSet<V> removeAll(Object key) {
447        throw new UnsupportedOperationException();
448      }
449    
450      /**
451       * Guaranteed to throw an exception and leave the multimap unmodified.
452       *
453       * @throws UnsupportedOperationException always
454       */
455      
456      @Override
457      public ImmutableSet<V> replaceValues(
458          K key, Iterable<? extends V> values) {
459        throw new UnsupportedOperationException();
460      }
461    
462      private transient ImmutableSet<Entry<K, V>> entries;
463    
464      /**
465       * Returns an immutable collection of all key-value pairs in the multimap.
466       * Its iterator traverses the values for the first key, the values for the
467       * second key, and so on.
468       */
469      // TODO(kevinb): Fix this so that two copies of the entries are not created.
470      
471      @Override
472      public ImmutableSet<Entry<K, V>> entries() {
473        ImmutableSet<Entry<K, V>> result = entries;
474        return (result == null)
475            ? (entries = ImmutableSet.copyOf(super.entries()))
476            : result;
477      }
478    
479      /**
480       * @serialData number of distinct keys, and then for each distinct key: the
481       *     key, the number of values for that key, and the key's values
482       */
483      @GwtIncompatible("java.io.ObjectOutputStream")
484      private void writeObject(ObjectOutputStream stream) throws IOException {
485        stream.defaultWriteObject();
486        Serialization.writeMultimap(this, stream);
487      }
488    
489      @GwtIncompatible("java.io.ObjectInputStream")
490      private void readObject(ObjectInputStream stream)
491          throws IOException, ClassNotFoundException {
492        stream.defaultReadObject();
493        int keyCount = stream.readInt();
494        if (keyCount < 0) {
495          throw new InvalidObjectException("Invalid key count " + keyCount);
496        }
497        ImmutableMap.Builder<Object, ImmutableSet<Object>> builder
498            = ImmutableMap.builder();
499        int tmpSize = 0;
500    
501        for (int i = 0; i < keyCount; i++) {
502          Object key = stream.readObject();
503          int valueCount = stream.readInt();
504          if (valueCount <= 0) {
505            throw new InvalidObjectException("Invalid value count " + valueCount);
506          }
507    
508          Object[] array = new Object[valueCount];
509          for (int j = 0; j < valueCount; j++) {
510            array[j] = stream.readObject();
511          }
512          ImmutableSet<Object> valueSet = ImmutableSet.copyOf(array);
513          if (valueSet.size() != array.length) {
514            throw new InvalidObjectException(
515                "Duplicate key-value pairs exist for key " + key);
516          }
517          builder.put(key, valueSet);
518          tmpSize += valueCount;
519        }
520    
521        ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
522        try {
523          tmpMap = builder.build();
524        } catch (IllegalArgumentException e) {
525          throw (InvalidObjectException)
526              new InvalidObjectException(e.getMessage()).initCause(e);
527        }
528    
529        FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
530        FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
531      }
532    
533      @GwtIncompatible("not needed in emulated source.")
534      private static final long serialVersionUID = 0;
535    }