public void testCreation_arrayOfArray() {
   String[] array = new String[] {"a"};
   Multiset<String[]> multiset = ImmutableMultiset.<String[]>of(array);
   Multiset<String[]> expected = HashMultiset.create();
   expected.add(array);
   assertEquals(expected, multiset);
 }
Esempio n. 2
0
 public void testCreateWithSize() {
   Multiset<String> multiset = HashMultiset.create(50);
   multiset.add("foo", 2);
   multiset.add("bar");
   assertEquals(3, multiset.size());
   assertEquals(2, multiset.count("foo"));
 }
  /** Test a TreeMultiset with a comparator that can return 0 when comparing unequal values. */
  public void testDegenerateComparator() throws Exception {
    TreeMultiset<String> ms = TreeMultiset.create(DEGENERATE_COMPARATOR);

    ms.add("foo");
    ms.add("a");
    ms.add("bar");
    ms.add("b");
    ms.add("c");

    assertEquals(2, ms.count("bar"));
    assertEquals(3, ms.count("b"));

    Multiset<String> ms2 = TreeMultiset.create(DEGENERATE_COMPARATOR);

    ms2.add("cat", 2);
    ms2.add("x", 3);

    assertEquals(ms, ms2);
    assertEquals(ms2, ms);

    SortedSet<String> elementSet = ms.elementSet();
    assertEquals("a", elementSet.first());
    assertEquals("foo", elementSet.last());
    assertEquals(DEGENERATE_COMPARATOR, elementSet.comparator());
  }
Esempio n. 4
0
 @Override
 public Multiset getValue(Multiset x, Multiset y) {
   Multiset out = new Multiset();
   out.addAll(x);
   out.addAll(y);
   return out;
 }
  public void testToString() {
    Multiset<String> ms = TreeMultiset.create();
    ms.add("a", 3);
    ms.add("c", 1);
    ms.add("b", 2);

    assertEquals("[a x 3, b x 2, c]", ms.toString());
  }
Esempio n. 6
0
 /** Returns {@code true} if the second list is a permutation of the first. */
 private static boolean isPermutation(List<?> first, List<?> second) {
   if (first.size() != second.size()) {
     return false;
   }
   Multiset<?> firstMultiset = HashMultiset.create(first);
   Multiset<?> secondMultiset = HashMultiset.create(second);
   return firstMultiset.equals(secondMultiset);
 }
 static <E> void a(Multiset<E> paramMultiset, ObjectOutputStream paramObjectOutputStream) {
   paramObjectOutputStream.writeInt(paramMultiset.a().size());
   Iterator localIterator = paramMultiset.a().iterator();
   while (localIterator.hasNext()) {
     Multiset.Entry localEntry = (Multiset.Entry) localIterator.next();
     paramObjectOutputStream.writeObject(localEntry.a());
     paramObjectOutputStream.writeInt(localEntry.b());
   }
 }
Esempio n. 8
0
 @GwtIncompatible // SerializableTester
 public void testSerializationIndirectSelfReference() {
   Multiset<MultisetHolder> multiset = HashMultiset.create();
   MultisetHolder holder = new MultisetHolder(multiset);
   multiset.add(holder, 2);
   Multiset<MultisetHolder> copy = SerializableTester.reserialize(multiset);
   assertEquals(2, copy.size());
   assertSame(copy, copy.iterator().next().member);
 }
Esempio n. 9
0
 /**
  * Returns a collection of multiset entries representing the counts of the distinct elements, in
  * sorted order. Does not check for null.
  */
 public static <E> Collection<Multiset.Entry<E>> sortedCounts(
     Comparator<? super E> comparator, Iterable<E> elements) {
   if (elements instanceof Multiset) {
     Multiset<E> multiset = (Multiset<E>) elements;
     if (hasSameComparator(comparator, elements)) {
       return multiset.entrySet();
     }
     List<Multiset.Entry<E>> entries = Lists.newArrayList(multiset.entrySet());
     Collections.sort(
         entries,
         Ordering.from(comparator)
             .onResultOf(
                 new Function<Multiset.Entry<E>, E>() {
                   @Override
                   public E apply(Entry<E> entry) {
                     return entry.getElement();
                   }
                 }));
     return entries;
   } else if (elements instanceof Set) { // known distinct
     Collection<E> sortedElements;
     if (hasSameComparator(comparator, elements)) {
       sortedElements = (Collection<E>) elements;
     } else {
       List<E> list = Lists.newArrayList(elements);
       Collections.sort(list, comparator);
       sortedElements = list;
     }
     return singletonEntries(sortedElements);
   } else if (hasSameComparator(comparator, elements)) {
     E current = null;
     int currentCount = 0;
     List<Multiset.Entry<E>> sortedEntries = Lists.newArrayList();
     for (E e : elements) {
       if (currentCount > 0) {
         if (comparator.compare(current, e) == 0) {
           currentCount++;
         } else {
           sortedEntries.add(Multisets.immutableEntry(current, currentCount));
           current = e;
           currentCount = 1;
         }
       } else {
         current = e;
         currentCount = 1;
       }
     }
     if (currentCount > 0) {
       sortedEntries.add(Multisets.immutableEntry(current, currentCount));
     }
     return sortedEntries;
   }
   TreeMultiset<E> multiset = TreeMultiset.create(comparator);
   Iterables.addAll(multiset, elements);
   return multiset.entrySet();
 }
Esempio n. 10
0
 /**
  * Returns {@code true} if {@code subMultiset.count(o) <= superMultiset.count(o)} for all {@code
  * o}.
  *
  * @since 10.0
  */
 public static boolean containsOccurrences(Multiset<?> superMultiset, Multiset<?> subMultiset) {
   checkNotNull(superMultiset);
   checkNotNull(subMultiset);
   for (Entry<?> entry : subMultiset.entrySet()) {
     int superCount = superMultiset.count(entry.getElement());
     if (superCount < entry.getCount()) {
       return false;
     }
   }
   return true;
 }
Esempio n. 11
0
  /** An implementation of {@link Multiset#setCount(Object, int, int)}. */
  static <E> boolean setCountImpl(Multiset<E> self, E element, int oldCount, int newCount) {
    checkNonnegative(oldCount, "oldCount");
    checkNonnegative(newCount, "newCount");

    if (self.count(element) == oldCount) {
      self.setCount(element, newCount);
      return true;
    } else {
      return false;
    }
  }
Esempio n. 12
0
 SerializedForm(Multiset<?> multiset) {
   int distinct = multiset.entrySet().size();
   elements = new Object[distinct];
   counts = new int[distinct];
   int i = 0;
   for (Entry<?> entry : multiset.entrySet()) {
     elements[i] = entry.getElement();
     counts[i] = entry.getCount();
     i++;
   }
 }
Esempio n. 13
0
 /**
  * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
  *
  * @param elements the {@code Iterable} to add to the {@code ImmutableMultiset}
  * @return this {@code Builder} object
  * @throws NullPointerException if {@code elements} is null or contains a null element
  */
 @Override
 public Builder<E> addAll(Iterable<? extends E> elements) {
   if (elements instanceof Multiset) {
     Multiset<? extends E> multiset = Multisets.cast(elements);
     for (Entry<? extends E> entry : multiset.entrySet()) {
       addCopies(entry.getElement(), entry.getCount());
     }
   } else {
     super.addAll(elements);
   }
   return this;
 }
Esempio n. 14
0
  /** An implementation of {@link Multiset#setCount(Object, int)}. */
  static <E> int setCountImpl(Multiset<E> self, E element, int count) {
    checkNonnegative(count, "count");

    int oldCount = self.count(element);

    int delta = count - oldCount;
    if (delta > 0) {
      self.add(element, delta);
    } else if (delta < 0) {
      self.remove(element, -delta);
    }

    return oldCount;
  }
Esempio n. 15
0
 /** An implementation of {@link Multiset#addAll}. */
 static <E> boolean addAllImpl(Multiset<E> self, Collection<? extends E> elements) {
   if (elements.isEmpty()) {
     return false;
   }
   if (elements instanceof Multiset) {
     Multiset<? extends E> that = cast(elements);
     for (Entry<? extends E> entry : that.entrySet()) {
       self.add(entry.getElement(), entry.getCount());
     }
   } else {
     Iterators.addAll(self, elements.iterator());
   }
   return true;
 }
  @Test
  public void whenGetTopUsingMultiSet_thenCorrect() {
    final Multiset<String> names = HashMultiset.create();
    names.add("John");
    names.add("Adam", 5);
    names.add("Jane");
    names.add("Tom", 2);

    final Set<String> sorted = Multisets.copyHighestCountFirst(names).elementSet();
    final List<String> topTwo = Lists.newArrayList(sorted).subList(0, 2);
    assertEquals(2, topTwo.size());
    assertEquals("Adam", topTwo.get(0));
    assertEquals("Tom", topTwo.get(1));
  }
  @Test
  public void whenInsertDuplicatesInMultiSet_thenInserted() {
    final Multiset<String> names = HashMultiset.create();
    names.add("John");
    names.add("Adam", 3);
    names.add("John");

    assertEquals(2, names.count("John"));
    names.remove("John");
    assertEquals(1, names.count("John"));

    assertEquals(3, names.count("Adam"));
    names.remove("Adam", 2);
    assertEquals(1, names.count("Adam"));
  }
Esempio n. 18
0
 /** An implementation of {@link Multiset#size}. */
 static int sizeImpl(Multiset<?> multiset) {
   long size = 0;
   for (Entry<?> entry : multiset.entrySet()) {
     size += entry.getCount();
   }
   return Ints.saturatedCast(size);
 }
Esempio n. 19
0
 /**
  * @param scores
  * @param restrictionSet
  * @return intersection of set (Multiset<Integer>) and restrictionSet (if restrictionSet non-null
  *     & non-empty); otherwise return set
  */
 public static Multiset<Integer> intersect(
     final Multiset<Integer> scores, final Set<Integer> restrictionSet) {
   if (restrictionSet != null && !restrictionSet.isEmpty()) {
     int prevSize = scores.size();
     Multiset<Integer> intersection = HashMultiset.create(scores);
     intersection.retainAll(restrictionSet);
     log.debug(
         prevSize != 0
             ? ("Size saving by retainAll = "
                     + (((prevSize - intersection.size()) * 100) / prevSize))
                 + "%"
             : "");
     return intersection;
   }
   return scores;
 }
Esempio n. 20
0
 // GWT compiler warning; see contains().
 @SuppressWarnings("cast")
 @Override
 public boolean remove(Object object) {
   if (object instanceof Multiset.Entry) {
     Entry<?> entry = (Entry<?>) object;
     Object element = entry.getElement();
     int entryCount = entry.getCount();
     if (entryCount != 0) {
       // Safe as long as we never add a new entry, which we won't.
       @SuppressWarnings("unchecked")
       Multiset<Object> multiset = (Multiset) multiset();
       return multiset.setCount(element, entryCount, 0);
     }
   }
   return false;
 }
 public void testCreation_arrayOfArray() {
   Comparator<String[]> comparator =
       Ordering.natural()
           .lexicographical()
           .onResultOf(
               new Function<String[], Iterable<Comparable>>() {
                 @Override
                 public Iterable<Comparable> apply(String[] input) {
                   return Arrays.<Comparable>asList(input);
                 }
               });
   String[] array = new String[] {"a"};
   Multiset<String[]> multiset = ImmutableSortedMultiset.orderedBy(comparator).add(array).build();
   Multiset<String[]> expected = HashMultiset.create();
   expected.add(array);
   assertEquals(expected, multiset);
 }
Esempio n. 22
0
  /** An implementation of {@link Multiset#removeAll}. */
  static boolean removeAllImpl(Multiset<?> self, Collection<?> elementsToRemove) {
    Collection<?> collection =
        (elementsToRemove instanceof Multiset)
            ? ((Multiset<?>) elementsToRemove).elementSet()
            : elementsToRemove;

    return self.elementSet().removeAll(collection);
  }
Esempio n. 23
0
  /** An implementation of {@link Multiset#retainAll}. */
  static boolean retainAllImpl(Multiset<?> self, Collection<?> elementsToRetain) {
    checkNotNull(elementsToRetain);
    Collection<?> collection =
        (elementsToRetain instanceof Multiset)
            ? ((Multiset<?>) elementsToRetain).elementSet()
            : elementsToRetain;

    return self.elementSet().retainAll(collection);
  }
Esempio n. 24
0
 @Override
 public int remove(Object element, int occurrences) {
   checkNonnegative(occurrences, "occurrences");
   if (occurrences == 0) {
     return count(element);
   } else {
     return contains(element) ? unfiltered.remove(element, occurrences) : 0;
   }
 }
Esempio n. 25
0
 @Override
 public int count(Object element) {
   int count = unfiltered.count(element);
   if (count > 0) {
     @SuppressWarnings("unchecked") // element is equal to an E
     E e = (E) element;
     return predicate.apply(e) ? count : 0;
   }
   return 0;
 }
Esempio n. 26
0
 @Override
 public boolean equals(@Nullable Object object) {
   if (object == this) {
     return true;
   }
   if (object instanceof Multiset) {
     Multiset<?> that = (Multiset<?>) object;
     if (this.size() != that.size()) {
       return false;
     }
     for (Entry<?> entry : that.entrySet()) {
       if (count(entry.getElement()) != entry.getCount()) {
         return false;
       }
     }
     return true;
   }
   return false;
 }
Esempio n. 27
0
 @SuppressWarnings("unchecked")
 @Override
 public Set<Multiset.Entry<E>> entrySet() {
   Set<Multiset.Entry<E>> es = entrySet;
   return (es == null)
       // Safe because the returned set is made unmodifiable and Entry
       // itself is readonly
       ? entrySet = (Set) Collections.unmodifiableSet(delegate.entrySet())
       : es;
 }
Esempio n. 28
0
 @Override
 Set<Entry<E>> createEntrySet() {
   return Sets.filter(
       unfiltered.entrySet(),
       new Predicate<Entry<E>>() {
         @Override
         public boolean apply(Entry<E> entry) {
           return predicate.apply(entry.getElement());
         }
       });
 }
Esempio n. 29
0
 /** Delegate implementation which cares about the element type. */
 private static <E> boolean retainOccurrencesImpl(
     Multiset<E> multisetToModify, Multiset<?> occurrencesToRetain) {
   checkNotNull(multisetToModify);
   checkNotNull(occurrencesToRetain);
   // Avoiding ConcurrentModificationExceptions is tricky.
   Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator();
   boolean changed = false;
   while (entryIterator.hasNext()) {
     Entry<E> entry = entryIterator.next();
     int retainCount = occurrencesToRetain.count(entry.getElement());
     if (retainCount == 0) {
       entryIterator.remove();
       changed = true;
     } else if (retainCount < entry.getCount()) {
       multisetToModify.setCount(entry.getElement(), retainCount);
       changed = true;
     }
   }
   return changed;
 }
Esempio n. 30
0
  /**
   * For each occurrence of an element {@code e} in {@code occurrencesToRemove}, removes one
   * occurrence of {@code e} in {@code multisetToModify}.
   *
   * <p>Equivalently, this method modifies {@code multisetToModify} so that {@code
   * multisetToModify.count(e)} is set to {@code Math.max(0, multisetToModify.count(e) -
   * occurrencesToRemove.count(e))}.
   *
   * <p>This is <i>not</i> the same as {@code multisetToModify.} {@link Multiset#removeAll
   * removeAll}{@code (occurrencesToRemove)}, which removes all occurrences of elements that appear
   * in {@code occurrencesToRemove}. However, this operation <i>is</i> equivalent to, albeit
   * sometimes more efficient than, the following:
   *
   * <pre>{@code
   * for (E e : occurrencesToRemove) {
   *   multisetToModify.remove(e);
   * }
   * }</pre>
   *
   * @return {@code true} if {@code multisetToModify} was changed as a result of this operation
   * @since 10.0 (missing in 18.0 when only the overload taking an {@code Iterable} was present)
   */
  public static boolean removeOccurrences(
      Multiset<?> multisetToModify, Multiset<?> occurrencesToRemove) {
    checkNotNull(multisetToModify);
    checkNotNull(occurrencesToRemove);

    boolean changed = false;
    Iterator<? extends Entry<?>> entryIterator = multisetToModify.entrySet().iterator();
    while (entryIterator.hasNext()) {
      Entry<?> entry = entryIterator.next();
      int removeCount = occurrencesToRemove.count(entry.getElement());
      if (removeCount >= entry.getCount()) {
        entryIterator.remove();
        changed = true;
      } else if (removeCount > 0) {
        multisetToModify.remove(entry.getElement(), removeCount);
        changed = true;
      }
    }
    return changed;
  }