What is the easiest way to iterate over all the key/value pairs of a java.util.Map in Java 5 and higher?
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With