按元素频率顺序迭代Multiset的最简单方法是什么?

问题描述:

考虑这个打印出一些设备类型统计数据的例子。 (DeviceType是具有十二个值的枚举。)

Consider this example which prints out some device type stats. ("DeviceType" is an enum with a dozenish values.)

Multiset<DeviceType> histogram = getDeviceStats();
for (DeviceType type : histogram.elementSet()) {
    System.out.println(type + ": " + histogram.count(type));
}

打印不同元素的最简单,最优雅的方法是什么?频率的顺序(最常见的类型是第一个)?

What's the simplest, most elegant way to print the distinct elements in the order of their frequency (most common type first)?

快速查看 Multiset 界面,没有现成的方法,也没有Guava的 Multiset 实现( HashMultiset TreeMultiset 等)似乎自动保留频率排序的元素。

With a quick look at the Multiset interface, there's no ready-made method for this, and none of Guava's Multiset implementations (HashMultiset, TreeMultiset, etc) seem to automatically keep elements frequency-ordered either.

我刚刚将此功能添加到Guava,请参阅 here 用于Javadoc。

I just added this feature to Guava, see here for the Javadoc.

编辑的使用示例Multisets.copyHighestCountFirst()根据原始问题:

Multiset<DeviceType> histogram = getDeviceStats();
for (DeviceType type : Multisets.copyHighestCountFirst(histogram).elementSet()) {
    System.out.println(type + ": " + histogram.count(type));
}