2010-11-05 19 views
5

Ho la prima coppia chiave/valore in un LinkedHashMap, che mi da un ciclo:Ottieni l'elemento successivo in LinkedHashMap?

for (Entry<String, String> entry : map.entrySet()) { 
    String key = entry.getKey(); 
    String value = entry.getValue(); 
    //put key value to use 
    break; 
} 

Successivamente, sulla base di un evento, ho bisogno della coppia chiave/valore successivo nella LinkedHashMap. Qual è il modo migliore per farlo?

+0

Più avanti nella stessa funzione o dove? – thattolleyguy

risposta

4

ottenere un iteratore e utilizzare hasNext() e next():

... 
Iterator<Entry<String, String>> it = map.entrySet().iterator(); 
if (it.hasNext()) { 
    Entry<String, String> first = it.next(); 
    ... 
} 
... 
if (eventHappened && it.hasNext()) { 
    Entry<String, String> second = it.next(); 
    ... 
} 
... 
1

Al posto di ogni ciclo, utilizzare un iteratore.

Iterator it = map.entrySet().iterator(); 
while (it.hasNext()) { 
    Map.Entry entry = (Map.Entry)it.next(); 
    String key = entry.getKey(); 
    String value = entry.getValue(); 
    // do something 
    // an event occurred 
    if (it.hasNext()) entry = (Map.Entry)it.next(); 
} 
1

La sua molto più facile avere il valore precedente, se è necessario confrontare i valori consecutivi.

String pkey = null; 
String pvalue = null; 
for (Entry<String, String> entry : map.entrySet()) { 
    String key = entry.getKey(); 
    String value = entry.getValue(); 

    // do something with pkey/key and pvalue/value. 

    pkey = key; 
    pvalue = value; 
} 
Problemi correlati