Jump to content

Associative array/Iteration: Difference between revisions

(Jakt)
Line 1,812:
 
=={{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> eentry : map.entrySet()) {
System.out.println("key = " + key + ", value = " + value);
System.out.println("key = " + keyentry);
}
</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 =: emap.getKeykeySet();)
 
System.out.println("value = " + valuekey);
// 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 (Stringint keyvalue : map.keySetvalues()) {
System.out.println("key = " + key + ", value = " + value);
</syntaxhighlight>
<br />
 
Java 8 version
118

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.