/** * 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(); }
@Override public SampleElements<Multiset.Entry<E>> samples() { SampleElements<E> samples = gen.samples(); return new SampleElements<Multiset.Entry<E>>( Multisets.immutableEntry(samples.e0, 3), Multisets.immutableEntry(samples.e1, 4), Multisets.immutableEntry(samples.e2, 1), Multisets.immutableEntry(samples.e3, 5), Multisets.immutableEntry(samples.e4, 2)); }
@Override public String toString() { return Multisets.immutableEntry(getElement(), getCount()).toString(); }