[英]What data structure could I use for counting occurrences of a country code?
我需要一些最不合适的数据结构。
以下是我正在使用的内容:我有一堆数据处理行,每行都有自己的国家/地区代码。
我希望得到每个国家/地区代码在整个过程中重复多少次。
您可以尝试HashMap 。 使用HashMap,您可以使用国家/地区代码作为密钥,并将每个显示的次数计为该密钥中存储的值。 如果您是第一次遇到特定的国家/地区代码,请将其插入到地图中,初始值为1; 否则,增加现有值。
HashMap<String, Integer> myMap = new HashMap<String, Integer>();
for (... record : records) {
String countryCode = record.getCountryCode();
int curVal;
if (myMap.containsKey(countryCode)) {
curVal = myMap.get(countryCode);
myMap.put(countryCode, curVal + 1);
} else {
myMap.put(countryCode, 1);
}
}
// myMap now contains the count of each country code, which
// can be used for whatever purpose needed.
我会使用HashMap,国家代码作为键,计数作为值。 从您的集合构建地图,并增加计数(如果它已经在地图中)。
使用国家/地区代码String作为键创建映射,将当前计数作为值。
当然,您意识到您可以直接从SQL查询中获取此类内容:
select country_code, count(country_code)
from your_table
group by country_code
order by country_code
您将获得包含国家/地区代码和计数对的ResultSet。 这很容易加载到地图中。
Guava提供AtomicLongMap
用HashMap之外的其他东西来完成答案。
int[]
或long[]
。 CountryCode
枚举并使用EnumMap存储金额: 例:
Map<CountryCode, Long> countryCodeAppearances =
new EnumMap<CountryCode,Long>(CountryCode.class);
轻量级数据结构将表现更好,并减少内存/垃圾收集开销。 所以,数组应该是最快的。 EnumMap是一种隐藏的宝石,在适当的情况下也可以为您带来性能提升。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.