2016-07-15 98 views
0

我有一個特定的HashMap,其中密鑰表示ClassModel的順序。衆所周知,HashMap在檢索或輸出時不保持鍵的順序。我也有一個ArrayList,它存儲了ClassModels的排列順序。例如,當我從HashMap中檢索關鍵值時,我會得到類似於Car 1,Car 4,Car 3,Car 5和Car 2的內容.ArrayList值具有預期的排列值順序;汽車1,汽車2,汽車3,汽車4和汽車5.我想根據ArrayList中的鍵來訂購它們。我的代碼如下:如何使用我自己的密鑰安排HashMap中的現有密鑰?

for (HashMap.Entry<String, FloorPlanModel> existingKeys : floorPlanKeys.entrySet()) { 
     Log.d(LOG_TAG, "existingKeys entries = " + existingKeys.getKey()); 
    } 
    for (String newKeys : buildingModel.getFpKeys()) { 
     Log.d(LOG_TAG, "newKeys entries = " + newKeys); 
    } 

而且輸出的時刻是:

existingKeys entries = floorplan0 
existingKeys entries = floorplan2 
existingKeys entries = floorplan3 
existingKeys entries = floorplan4 
existingKeys entries = floorplan1 

newKeys entries = floorplan0 
newKeys entries = floorplan1 
newKeys entries = floorplan2 
newKeys entries = floorplan3 
newKeys entries = floorplan4 

我應該把第二個for循環的第一個內部的循環,但在如何遍歷每個值HashMap並將它們與ArrayList中的一個排序?如果我覆蓋它們,hashmap中的值是否會改變?

我忘了提及我無法爲此使用TreeMaps。我需要手動安排它們。

回答

2

TreeMap是你的朋友。映射分類/可排序的鍵。

+0

好吧我忘了提及,我目前無法使用TreeMaps,因爲從Firebase(僅將數據存儲在HashMaps中)中檢索數據並將其直接輸入到ExpandableListAdapter(我必須插入值進入小孩和小組,其中包含整數中的位置)。所以我會迭代它們並手動重新排列它們。 – user3056928

+2

'新的TreeMap(myHashMap)'將會轉換它。 – jiggy

相關問題