Issue
DATA
CountryInfo
public class CountryInfo {
private String country;
private String countryCode;
private String currency;
@Id
private String state;
private String stateCode;
private String statePopulation;
public HashMap<String, Integer> getAllCountryPopulations(){
List<CountryInfo> countries = countrySqlRepository.findAll();
HashMap<String, Integer> populations = new HashMap<>();
Integer sumOfPopulation = 0;
HashSet<String> set = new HashSet<String>();
for(int i=0; i<countries.size(); i++){
CountryInfo countryInfo = countries.get(i);
set.add(countryInfo.getCountryCode());
if(set.contains(countryInfo.getCountryCode())){
sumOfPopulation += Integer.parseInt(countryInfo.getStatePopulation().replaceAll(",", ""));
}
populations.put(countryInfo.getCountryCode(), sumOfPopulation);
}
return populations;
}
I am trying to return the sum of values for a given map on unique country codes. Instead of returning the corresponding sum for each key in the set I am getting the sum of all values within the set.
Example:
{America: 4329392, Canada: 13025402}
Should be
{America: 4329392, Canada: 8721010}
How do I fix my logic here?
Thanks in advance.
Solution
In your logic, the problem is
Integer sumOfPopulation = 0;
should be defined inside your for loop as it will be different for each country.
Off-topic, you don't even need a set, a single HashMap will work here.
final List<CountryInfo> countries = countrySqlRepository.findAll();
final HashMap<String, Integer> populations = new HashMap<>();
for (final CountryInfo countryInfo : countries) {
final int sum = populations.getOrDefault(countryInfo.getCountryCode(), 0);
final int population = Integer.parseInt(countryInfo.getStatePopulation().replaceAll(",", ""));
populations.put(countryInfo.getCountryCode(), population + sum);
}
return populations;
Answered By - Ankit Sharma Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.