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.
for (Map.Entry<String, Integer> e : map.entrySet()) {
</p>
String key = e.getKey();
<syntaxhighlight lang="java">
Integer value = e.getValue();
for (Map.Entry<String, Integer> entry : map.entrySet())
System.out.println("key = " + key + ", value = " + value);
System.out.println(entry);
}
</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>.
for (String key : map.keySet()) {
</p>
System.out.println("key = " + key);
<syntaxhighlight lang="java">
}
for (String key : map.keySet())

System.out.println(key);
// iterating over values:
</syntaxhighlight>
for (Integer value : map.values()) {
<p>
System.out.println("value = " + value);
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>.
}</syntaxhighlight>
</p>
<syntaxhighlight lang="java">
for (int value : map.values())
System.out.println(value);
</syntaxhighlight>
<br />


Java 8 version
Java 8 version