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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With