2016-02-05 54 views
0

我遇到一個很奇怪的地方出現一個HashMap變量HashMap的迭代器中收集

HashMap<Integer, String> locationCatalog = new HashMap<>(); 

將正確迭代(即開始在第一個數字鍵)不開始第一個鍵,有時不。我遍歷Excel文檔(使用外部庫)以獲取單元格值,並根據單元格將其放入基於單元格的行和列座標的HashMap中。

locationCatalog.put(row.getRowNum(), cell.getStringCellValue().trim()); 

所有的數據被填充後,我通過locationCatalog迭代,以獲得內容:

Set set = locationCatalog.entrySet(); 
Iterator trimIterator = set.iterator(); 
System.out.println(lastLabelName + " - locationCatalog contents (run #1):"); 
while (trimIterator.hasNext()) { 
    Map.Entry locationMap = (Map.Entry)trimIterator.next(); 
    System.out.println("Key: " + (int) locationMap.getKey() + ", Row: " + ((int) locationMap.getKey() + 1) + ", Location: " + locationMap.getValue().toString()); 
    ... 
} 

這裏是打印出來的良好運行的:

BALI - locationCatalog contents (run #1): 
Key: 16, Row: 17, Location: S082025 E1150531 
Key: 17, Row: 18, Location: S082025 E1150531 
Key: 18, Row: 19, Location: 
Key: 19, Row: 20, Location: S082025 E1150531 
Key: 20, Row: 21, Location: 
Key: 21, Row: 22, Location: S082025 E1150531 

的異常發生零星。當我移動一個單元格而不是僅僅複製和粘貼內容時,它似乎開始了。一旦我明白了這一點,我將put方法調整爲僅使用一個獨立於Excel源的常規整數。但是,這一調整並未改變結果。這是一個糟糕的運行的一個例子:

BALI - locationCatalog contents (run #1): 
Key: 16, Row: 17, Location: S08 20 25 E115 05 31 
Key: 17, Row: 18, Location: 
Key: 18, Row: 19, Location: 
Key: 9, Row: 10, Location: S08 20 25 E115 05 31 
Key: 10, Row: 11, Location: S08 20 25 E115 05 31 
Key: 11, Row: 12, Location: 
Key: 12, Row: 13, Location: S08 20 25 E115 05 31 
Key: 13, Row: 14, Location: 
Key: 14, Row: 15, Location: S08 20 25 E115 05 31 
Key: 15, Row: 16, Location: S08 20 25 E115 05 31 

而不能發佈Excel文件的截圖,細胞就該運行而言,開始在第10行,並繼續到行19.然而,當它通過迭代locationCatalog,它不以最低的鍵,在這種情況下的鍵9開始。這是一個問題,因爲我必須多次迭代這個HashMap來獲得最終產品,並且需要按照升序排列。在完成收集後,我將其清除並開始填充一組新數據。

如果我切和相同的細胞粘貼到不同的行,結果(正確地)更改爲:

BALI - locationCatalog contents (run #1): 
Key: 4, Row: 5, Location: S08 20 25 E115 05 31 
Key: 5, Row: 6, Location: S08 20 25 E115 05 31 
Key: 6, Row: 7, Location: 
Key: 7, Row: 8, Location: S08 20 25 E115 05 31 
Key: 8, Row: 9, Location: 
Key: 9, Row: 10, Location: S08 20 25 E115 05 31 
Key: 10, Row: 11, Location: S08 20 25 E115 05 31 
Key: 11, Row: 12, Location: S08 20 25 E115 05 31 
Key: 12, Row: 13, Location: 
Key: 13, Row: 14, Location: 

我一直在努力了一個星期,現在要弄清楚是怎麼回事,到包括更改HashMap的參數,所有這些都沒有運氣。希望有更多智力和Java專業知識的人可以伸出援助之手。

回答

1

您認爲HashMaps按給定順序返回它們的條目是錯誤的。改爲使用OrderedMap的實現,如TreeMap

+1

@ ave8tor也許就像樹圖一樣...?像... https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html – SirDarius

+1

感謝您的協助!事實證明,我只需要使用TreeMap而不是HashMap來獲得我正在尋找的東西。令我感到沮喪的是,答案非常簡單,我花了整整一週的空閒時間嘗試所有可能的事情,以便理解爲什麼它按照它的方式迭代它。 – ave8tor

+0

@SirDarius感謝您的更正,這就是我的意思 – Drunix