Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data structure could I use for counting occurrences of a country code?

I need some kind of data structure don't know yet which would be most suitable.

Here is what I'm working with: I have a bunch rows of data processing and each row has its own country code.

I want to obtain as result how many times each country code repeats throughout the process.

like image 284
London Avatar asked Sep 21 '11 19:09

London


3 Answers

You might try a HashMap. With a HashMap, you can use the country code as the key, and the count of how many times each appears as the value stored in that key. If you encounter a particular country code for the first time, insert it into the map with an initial value of 1; otherwise, increment 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.
like image 179
mellamokb Avatar answered Sep 19 '22 01:09

mellamokb


I would use a HashMap with the country code as the key and the count as the value. Build the map from your collection and increment the count if it is already in the map.

like image 32
smp7d Avatar answered Sep 21 '22 01:09

smp7d


Create a Map using country code String as the key and the current count as the value.

You realize, of course, that you can get such a thing directly out of a SQL query:

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

You'll get a ResultSet with country code and count pairs. That's easy to load into a Map.

like image 20
duffymo Avatar answered Sep 18 '22 01:09

duffymo