Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sum values in a map efficiently within java

DATA

enter image description here

CountryInfo

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading