按元素频率顺序迭代Multiset的最简单方法是什么? [英] Simplest way to iterate through a Multiset in the order of element frequency?

查看:77
本文介绍了按元素频率顺序迭代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));
}

这篇关于按元素频率顺序迭代Multiset的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆