What data structure could I use to count the occurrences of a country code?

I need some kind of data structure, I don’t know yet what would be the most suitable.

Here's what I work with: I have a series of data processing lines, and each line has its own country code.

I want to get as a result, how many times each country code is repeated throughout the process.

+5
source share
5 answers

You can try HashMap . Using HashMap, you can use the country code as a key, and the number of times how many times each is displayed as the value stored in this key. If this is your first time encountering a specific country code, insert it into the map with an initial value of 1; otherwise increase the existing value.

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.
+7
source

I would use a HashMap with a country code as a key and a counter as a value. Create a card from your collection and increase the number if it is already on the card.

+3
source

, . .

, , ​​ SQL-:

select country_code, count(country_code)
from your_table
group by country_code
order by country_code

ResultSet . .

+2

-, HashMap.

:

Map<CountryCode, Long> countryCodeAppearances = 
       new EnumMap<CountryCode,Long>(CountryCode.class);

/. , . EnumMap , .

0
0

All Articles