简体   繁体   English

Hashmap - 返回键并将其设置为 object 的值

[英]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 .我有两个 CSV 文件,一个"crimeUSA.csv" ,标题statecitypopulation等,还有一个StatesAbbreviations ,标题为states, abbrev First I read the "crimeUSA.csv" file and create CityCrime objects.首先,我读取"crimeUSA.csv"文件并创建CityCrime对象。

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.我不想在此文件中使用 state,而是想将其与StatesAbbreviations文件中的 state 相匹配,并将 state 设置为适当的缩写值。 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.我以前在 state 的 setter 中硬编码了状态和匹配的缩写,但我已经删除了它,因为它又长又丑。 In the readCrimeData() method is where I am creating the instances of the CityCrime object, so crime.setState(stats[1]);readCrimeData()方法中,我创建了CityCrime object 的实例,因此crime.setState(stats[1]); is commented out as I do not wanted the state/abbreviation hardcoded anymore.被注释掉了,因为我不想再对状态/缩写进行硬编码。

This is the StartApp class:这是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:城市CityCrime

    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.我的目标是有一个setAbbreviation,所以取CityCrime CSV的state值,与CityCrime class中的StatesAbbreviation基本匹配,设置为匹配缩写。 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.你可能会说,我对Java比较陌生,所以请尽量通俗易懂地解释一下,以帮助我理解。

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, ie:readAbbrevData方法的返回类型从void更改为Map<String,String>以返回 map 而不是仅将其打印到控制台,即:

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在您的readCrimeData方法中处理您的犯罪数据文件之前调用上述方法以获取 map 并使用它来设置您的缩写

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]);
       }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM