2016-11-19 48 views
1

有沒有辦法從一個特定的鍵開始在HashMap中迭代?如何從Java中的特定鍵值開始遍歷HashMap?

假設我的地圖是:

Map map = new HashMap(); 
map.put(1,"A"); 
map.put(2,"B"); 
map.put(3,"B"); 
map.put(4,"B"); 
map.put(5,"F"); 
map.put(6,"Z"); 

而且我要重複,將來自主要2開始。

常規迭代包括:

public static void printMap(Map map) { 
    Iterator it = map.entrySet().iterator(); 
     while (it.hasNext()) { 
      Map.Entry pair = (Map.Entry)it.next(); 
      System.out.println(pair.getKey() + " = " + pair.getValue()); 
     } 
} 

但是如何從一個特定的鍵啓動迭代?

+4

由於迭代順序未定義,您無法使用HashMap執行此操作。你想要一個TreeMap(或者查看你的索引,也許只是一個數組或列表)。 – Thilo

+1

另外,在你的例子中,你將'map'定義爲[原始類型](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-用它)。最好不要這樣做(見鏈接)。嘗試使用Map map = new HashMap ()'。 :) – Gulllie

+0

您是否使用地圖上的鍵(1,2,3,...)作爲某種索引?還是僅僅爲了這個例子? – smsnheck

回答

5

你的問題是基於一個什麼樣的HashMap是一種誤解,你可以使用。特別是,如果你開始在關鍵2和迭代剩餘的條目,有不能保證,你會得到的鑰匙23456條目...的順序,或以任何順序。

HashMap的迭代順序未定義,並且在大多數情況下不可預測。

但是...如果你使用的LinkedHashMapTreeMap和重複的條目,那麼你會得到他們所定義的順序:

  • 一個LinkedHashMap會(一般)在給廣告訂單中的條目
  • a TreeMap將按鍵的比較順序給出條目。

如果您使用LinkedHashMap,從給定鍵(按插入順序)開始獲取所有條目的方法是從開始迭代直到找到所需的鍵。例如:

public static void printMapFrom(LinkedHashMap<K, V> map, K from) { 
    boolean found = false; 
    for (Map<K, V>.Entry entry : map.entrySet()) { 
     if (!found && !from.equals(entry.getKey())) { 
      continue; 
     } 
     found = true; 
     System.out.println(entry.getKey() + " = " + entry.getValue()); 
    } 
} 

如果使用TreeMap的方式做到這一點是使用tailMap(key)從關鍵到最後得到的條目的子圖。然後你迭代子圖。

public static void printMapFrom(SortedMap<K, V> map, K from) { 
    for (Map<K, V>.Entry entry : map.tailMap(from).entrySet()) { 
     System.out.println(entry.getKey() + " = " + entry.getValue()); 
    } 
} 

如果你真的不在乎鍵在HashMap的順序是不確定的,那麼你可以使用LinkedHashMap版本以上普通HashMapConcurrentHashMap

-1

先定義你的map Map<Integer, String> map = new LinkedHashMap<Integer,String>(); 然後像它

for(Map.Entry<Integer, String> entry: map.entrySet()){ 
    if(entry.getKey() == 1){ 
     continue; 
    } 
    System.out.println(entry.getKey() +" : "+ entry.getValue()); 
} 
+0

這隻適用於以「秒」鍵開頭的情況。此外,它忽略了迭代順序不可預測的事實。 –

+0

感謝您更新我我已將HashMap更改爲linkedHashMap –

+0

它將保留插入順序 –