我有一個HashMap,鍵的值是一個ArrayList。當我逐行讀取文件時,我需要添加到屬於該特定鍵的ArrayList。 該文件可能有1行或100萬行,關鍵名稱將是行(String),它的值將表示它在文件中出現的行號。如何添加到迭代時是一個HashMap值的ArrayList?
有人可以幫我嗎?此外,這是快速的時間複雜性明智嗎?如果不是,我該如何優化它?
例的test.txt:
Hello <== Line 0
Jello <== Line 1
Mello <== Line 2
Hello <== Line 3
Tello <== Line 4
Jello <== Line 5
Tello <== Line 6
Tello <== Line 7
我需要我的地圖存儲內容(忽略順序):
{"Hello": [0, 3]}
{"Jello": [1, 5]}
{"Mello": [2]}
{"Tello": [4, 6, 7]}
我的代碼是:
ArrayList<Integer> al = new ArrayList<Integer>();
Map<String, ArrayList<Integer>> hm = new HashMap<String, ArrayList<Integer>>();
int num = 0;
for (String line = file.readLine(); line != null; line = file.readLine()) {
map.put(line, al.add(num)); <== the issue is here, how to fix?
}
編譯器錯誤:
incompatible types: boolean cannot be converted to ArrayList<Integer>
調用'al.add(num);'作爲一個單獨的語句,然後使用'map.put(line,num);' – MadProgrammer