将文件读入 HashMap
Reading file into HashMap
我正在阅读包含城市及其人口的文件。
文件如下所示:
纽约市
纽约州 8,175,133
洛杉矶市
加州 3,792,621
.......
原始文件的格式不同,但我无法修改我的代码以正确读取它。原始文件如下所示:
纽约市 NY 8,175,133
加利福尼亚州洛杉矶市 3,792,621
............
我发布了适用于第一个版本的代码(如下),但我怎样才能让它适用于原始格式?我试图让城市成为我的关键,让州和人口成为价值。
我知道这很简单,但我不知道它是什么。
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));
}
}
谢谢。
只需将调用 readLine
的代码替换为如下代码:
String line = scannner.readLine();
int space = line.lastIndexOf(' ', line.lastIndexOf(' ') - 1);
String city = line.substring(0,space);
String statepop = line.substring(space+1);
然后将您的 city
和 statepop
放入您的地图。
基本上,此代码会找到倒数第二个 space 并在那里拆分您的 String
。
可能是这样的:
while (reader.hasNext())
{
String line = reader.nextLine();
int splitIndex = line.lastIndexOf(" city ");
data.put(line.substring(0, splitIndex + 5), line.substring(splitIndex + 6));
}
我正在阅读包含城市及其人口的文件。
文件如下所示:
纽约市
纽约州 8,175,133
洛杉矶市
加州 3,792,621
.......
原始文件的格式不同,但我无法修改我的代码以正确读取它。原始文件如下所示:
纽约市 NY 8,175,133
加利福尼亚州洛杉矶市 3,792,621
............
我发布了适用于第一个版本的代码(如下),但我怎样才能让它适用于原始格式?我试图让城市成为我的关键,让州和人口成为价值。 我知道这很简单,但我不知道它是什么。
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));
}
}
谢谢。
只需将调用 readLine
的代码替换为如下代码:
String line = scannner.readLine();
int space = line.lastIndexOf(' ', line.lastIndexOf(' ') - 1);
String city = line.substring(0,space);
String statepop = line.substring(space+1);
然后将您的 city
和 statepop
放入您的地图。
基本上,此代码会找到倒数第二个 space 并在那里拆分您的 String
。
可能是这样的:
while (reader.hasNext())
{
String line = reader.nextLine();
int splitIndex = line.lastIndexOf(" city ");
data.put(line.substring(0, splitIndex + 5), line.substring(splitIndex + 6));
}