If you used Guava's Multiset
instead of Apache's Bag
-- roughly analogous, but in a different style -- you can do most of this without converting. Multiset.entrySet()
returns a Set<Entry<E>>
, with Entry<E>
effectively representing a pair of an element and a count -- that sounds like it's probably the best way to address your need to operate on the element-count pairs, maybe? You can iterate over that like you'd iterate over a Map.entrySet()
.
You can use Multisets.copyHighestCountFirst(Multiset)
to get a multiset reordered in highest-frequency-first order, and use TreeMultiset
to order by the elements directly.
(Disclosure: I contribute to Guava.)