简体   繁体   中英

Reading file into HashMap

I am reading a file with the city and its population.

the file looks like this:

New York city

NY 8,175,133

Los Angeles city

CA 3,792,621

............

The format of the original file is different but I can't modify my code to read it properly. The original file looks like this:

New York city NY 8,175,133

Los Angeles city CA 3,792,621

...........

I posted the code (below) that works for the first version, but how can I make it to work for the original format? I am trying to make the city my key and the state & population as the value. I know it's something simple but I can't figure out what it is.

public static void main(String[] args) throws FileNotFoundException
{
    File file = new File("test.txt");
    Scanner reader = new Scanner(file);
    HashMap<String, String> data = new HashMap<String, String>();
    while (reader.hasNext())
    {
        String city = reader.nextLine();
        String state_pop = reader.nextLine();
        data.put(city, state_pop);
    }
    Iterator<String> keySetIterator = data.keySet().iterator();
    while (keySetIterator.hasNext())
    {
        String key = keySetIterator.next();
        System.out.println(key + "" + data.get(key));
    }
}

Thank you.

Just replace your code where you call readLine with something like this:

String line = scannner.readLine();
int space = line.lastIndexOf(' ', line.lastIndexOf(' ') - 1);
String city = line.substring(0,space);
String statepop = line.substring(space+1);

then put your city and statepop into your map.

Basically, this code finds the second last space and splits your String there.

Perhaps something like:

while (reader.hasNext())
{
    String line = reader.nextLine();
    int splitIndex = line.lastIndexOf(" city ");            

    data.put(line.substring(0, splitIndex + 5), line.substring(splitIndex + 6));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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