Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to iterate over all the key/value pairs of a java.util.Map in Java 5 and higher?

What is the easiest way to iterate over all the key/value pairs of a java.util.Map in Java 5 and higher?

like image 923
flybywire Avatar asked Feb 25 '09 11:02

flybywire


People also ask

How do you iterate over keys and values of a Map?

Iterating over Map. Entry<K, V>>) of the mappings contained in this map. So we can iterate over key-value pair using getKey() and getValue() methods of Map. Entry<K, V>. This method is most common and should be used if you need both map keys and values in the loop.

How do I efficiently iterate over each entry in a Java list?

forEach() Since Java 8, we can use the forEach() method to iterate over the elements of a list. This method is defined in the Iterable interface, and can accept Lambda expressions as a parameter.


1 Answers

Assuming K is your key type and V is your value type:

for (Map.Entry<K,V> entry : map.entrySet()) {   K key = entry.getKey();   V value = entry.getValue();   // do stuff } 
like image 158
Joachim Sauer Avatar answered Oct 10 '22 01:10

Joachim Sauer