PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] How to sum values in a map efficiently within java

 September 20, 2022     hashmap, java, sum     No comments   

Issue

DATA

enter image description here

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing