Associative array/Iteration: Difference between revisions
Content added Content deleted
(Jakt) |
|||
Line 1,812: | Line 1,812: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
<p> |
|||
<syntaxhighlight lang="java">Map<String, Integer> map = new HashMap<String, Integer>(); |
|||
See also, [https://rosettacode.org/wiki/Associative_array/Iteration#Java Java - Associative array/Iteration]. |
|||
map.put("hello", 1); |
|||
</p> |
|||
map.put("world", 2); |
|||
<p> |
|||
map.put("!", 3); |
|||
You can access the <kbd>key</kbd> and <kbd>value</kbd> pairs by using the <code>Map.entrySet</code> method, |
|||
which will return a <code>Map.Entry</code>.<br /> |
|||
// iterating over key-value pairs: |
|||
It's worth noting that a <code>Map.Entry</code> also has the <code>setValue</code> method. |
|||
⚫ | |||
</p> |
|||
⚫ | |||
⚫ | |||
Integer value = e.getValue(); |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} |
|||
</syntaxhighlight> |
|||
<p> |
|||
// iterating over keys: |
|||
You can access just the <kbd>key</kbd>s by using the <code>Map.keySet</code> method, which will return a <code>Set</code>. |
|||
⚫ | |||
</p> |
|||
⚫ | |||
<syntaxhighlight lang="java"> |
|||
} |
|||
⚫ | |||
⚫ | |||
// iterating over values: |
|||
</syntaxhighlight> |
|||
for (Integer value : map.values()) { |
|||
<p> |
|||
⚫ | |||
And you can access just the <kbd>value</kbd>s by using the <code>Map.values</code> method, which will return a <code>Collection</code>. |
|||
⚫ | |||
</p> |
|||
<syntaxhighlight lang="java"> |
|||
⚫ | |||
⚫ | |||
</syntaxhighlight> |
|||
<br /> |
|||
Java 8 version |
Java 8 version |