我可以使用什么数据结构来计算国家/地区代码的出现次数?

Lon*_*don 6 java data-structures

我需要一些最不合适的数据结构.

以下是我正在使用的内容:我有一堆数据处理行,每行都有自己的国家/地区代码.

我希望得到每个国家/地区代码在整个过程中重复多少次.

mel*_*okb 8

您可以尝试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.
Run Code Online (Sandbox Code Playgroud)

  • 在Java中,您无法使用原始数字类型进行参数化.你必须使用`Integer`而不是`int`. (4认同)