Skip to content
Advertisement

Hashmap – returning key and setting it as value of an object

I have two CSV files, one "crimeUSA.csv" with the headers state, city, population etc. and one StatesAbbreviations with the headers states, abbrev . First I read the "crimeUSA.csv" file and create CityCrime objects.

Instead of using the state in this file, I want to match it with the state in the StatesAbbreviations file and set the state as the appropriate abbreviation value instead. I previously had the states and matching abbreviations hardcoded in the setter for state but I have removed it as was pretty long and ugly. In the readCrimeData() method is where I am creating the instances of the CityCrime object, so crime.setState(stats[1]); is commented out as I do not wanted the state/abbreviation hardcoded anymore.

This is the StartApp class:

public static void main(String[] args) {

        try {
            CityCrime.readAbbrevData();
            readCrimeData("crimeUSA.csv");
            System.out.println("Total cities read: " + getTotalCities());
            showMenu();
        } catch (Exception e) {

            e.printStackTrace();
        }
    }
    
    /**
     * Reads the crime data for each city from entered file
     * Adds the CityCrime objects to the crimes ArrayList
     */
    public static void readCrimeData(String fromFile) {

        File file = new File(fromFile);

        FileReader fileReader;
        BufferedReader bufferedReader;
        
        String crimeInfo;
        String[] stats;
        try {
            fileReader = new FileReader(file);
            bufferedReader = new BufferedReader(fileReader);

            crimeInfo = bufferedReader.readLine();
            crimeInfo = bufferedReader.readLine();

            do {
                CityCrime crime = new CityCrime(); // Default constructor
                stats = crimeInfo.split(",");
                {
                    if (stats[0] != null) {
                        crime.setCity(stats[0]);
                    }
                    if (stats[1] != null) {
                        crime.setAbbreviation(stats[1]);
                        //crime.setState(stats[1]);
                    }
                    if (stats[2] != null) {
                        if (Integer.parseInt(stats[2]) >= 0) {
                            crime.setPopulation(Integer.parseInt(stats[2]));
                        }
                    }
                    if (stats[3] != null) {
                        if (Integer.parseInt(stats[3]) >= 0) {
                            crime.setMurder(Integer.parseInt(stats[3]));
                        }
                    }

                    if (stats[4] != null) {
                        if (Integer.parseInt(stats[4]) >= 0) {
                            crime.setRobbery(Integer.parseInt(stats[4]));
                        }
                    }

                    if (stats[5] != null) {
                        if (Integer.parseInt(stats[5]) >= 0) {
                            crime.setAssault(Integer.parseInt(stats[5]));
                        }
                    }

                    if (stats[6] != null) {
                        if (Integer.parseInt(stats[6]) >= 0) {
                            crime.setBurglary(Integer.parseInt(stats[6]));
                        }
                    }

                    if (stats[7] != null) {
                        if (Integer.parseInt(stats[7]) >= 0) {
                            crime.setLarceny(Integer.parseInt(stats[7]));
                        }
                    }

                    if (stats[8] != null) {
                        if (Integer.parseInt(stats[8]) >= 0) {
                            crime.setMotorTheft(Integer.parseInt(stats[8]));
                        }
                    }
                    crime.setTotalCrimes(Integer.parseInt(stats[3]), Integer.parseInt(stats[4]), Integer.parseInt(stats[5]), Integer.parseInt(stats[6]), Integer.parseInt(stats[7]), Integer.parseInt(stats[8]));
                }
                crimes.add(crime);
                System.out.println(crime);

                crimeInfo = bufferedReader.readLine();

            } while (crimeInfo != null);

            fileReader.close();
            bufferedReader.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
    public static void readAbbrevData() {

        File file = new File("StatesAbbreviations.csv");
        var stateToAbbreviation = new HashMap<String, String>();
        
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
            String abbrevInfo;
            while ((abbrevInfo = bufferedReader.readLine()) != null) {
                String[] stats = abbrevInfo.split(",");
                // stats[0] may be empty, but never null, no check required
                stateToAbbreviation.put(stats[0], stats[1]);
            }
        } catch (IOException e) {
            throw new RuntimeException("Could not read state / abbreviations from CSV file", e);
        }
        
        for (String key: stateToAbbreviation.keySet()){
            System.out.println(key +" = "+stateToAbbreviation.get(key));
        }
    }

The CityCrime class:

    public static void main(String[] args) {
        
        
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }
    
    public void setState(String state) {
        this.state = state;
    }


    public int getPopulation() {
        return population;
    }


    public void setPopulation(int population) {
        this.population = population;

    }
    //etc
    

    @SuppressWarnings("null")
    public String setAbbreviation(String state) {
        return stateToAbbreviation.getOrDefault(state,"UNKNOWN");
        }

My aim is to have a setAbbreviation, so it takes the state value of the CityCrime CSV, basically matches it with the state in the StatesAbbreviation class, and sets it as the matching abbreviation. As you can probably tell, I am relatively new to Java, so please try and explain in simple terms as possible to help my understanding.

Advertisement

Answer

Change the return type of your readAbbrevData method from void to Map<String,String> to return a map instead of just printing it out to console, i.e:

public static Map<String,String> readAbbrevData() {
    File file = new File("StatesAbbreviations.csv");
    var stateToAbbreviation = new HashMap<String, String>();

    // ....
   return stateToAbbreviation
}

Call the above method before processing your crime data file in your readCrimeData method to get the map and use it to set your abrivations

public static void readCrimeData(String fromFile) {

    Map<String,String> myMap = readAbbrevData();
    File file = new File(fromFile);
    ....


       if (stats[1] != null) {
             crime.setAbbreviation(myMap.get(stats[1]));
            //crime.setState(stats[1]);
       }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement