2015-04-30 51 views
0

我有一個文本文件,每行代表一個時區。 timezone.txtJava創建收集和出現次數

我希望我的程序能夠逐行進行並計算整個文件中的時區數量。

樣本:

Eastern 
Eastern 
West 
Eastern 
West 
West 
Eastern 
Mountain 
West 

然後給我的列表,時區和occurances

[(West, 4), (Eastern, 4), (Mountain, 1)] 

不同的時區的數量在程序開始未知的數量。到目前爲止,我的代碼只能打印每個時區,但不知道如何在java中創建這個數組。

public static void main(String[] args) { 

     try { 
     BufferedReader in = new BufferedReader(new FileReader("timezones.txt")); 

     String line = null; 
     while ((line = in.readLine()) != null) { 
      System.out.println(line); 
     } 
    } catch (IOException e){ 
     e.printStackTrace(); 
    } 

} 
+2

使用地圖<字符串,整數>。 – Masudul

+0

在發佈之前,您可以在while循環內嘗試一些內容。 –

回答

3

創建一個Map<String, Integer>以存儲與每個時區關聯的計數。當您讀取時區名稱時,請檢索以該名稱存儲的Integer(如果有),將其增加,並將更新的計數存回地圖。如果名稱未在地圖中出現,請存儲計數1.完成後,您可以檢索所有<String, Integer>條目並打印您的列表。

1

您應該使用像Map<String, Integer>這樣的地圖,其中密鑰將是String,值將是Integer。比通過該文件循環,並將StringMap並計數值。

while ((line = in.readLine()) != null) { 
    Integer count= map.get(line); 
    map.put(line, count == null ? 1 : count+1); 
} 
1

使用lambda表達式:

try (BufferedReader in = new BufferedReader(new FileReader("timezones.txt"))) { 
     Map<String, Integer> map = new HashMap<>(); 
     in.lines().forEach(line -> { 
      Integer count = map.get(line); 
      map.put(line, count == null ? 1 : count + 1); 
     }); 
     System.out.println(map); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

或使用用於:

 Map<String, Integer> map = new HashMap<>(); 
     for (String line; null != (line = in.readLine());) { 
      Integer count = map.get(line); 
      map.put(line, count == null ? 1 : count + 1); 
     } 
     System.out.println(map);