Associative array/Creation: Difference between revisions

Content added Content deleted
Line 2,809: Line 2,809:
<syntaxhighlight lang="java">Int? mightBeNull = map["foo"];
<syntaxhighlight lang="java">Int? mightBeNull = map["foo"];
Int neverNull = map.getOrDefault("foo", 0);
Int neverNull = map.getOrDefault("foo", 0);
if (Int n := map.get("foo"))
if (Int n := map.get("foo")) {
{
// if "foo" is in the map, then the variable "n" is set to its value
// if "foo" is in the map, then the variable "n" is set to its value
} else {
}
else
{
// if "foo" is not in the map, then the variable "n" is not defined
// if "foo" is not in the map, then the variable "n" is not defined
}</syntaxhighlight>
}</syntaxhighlight>
Iterate over keys:
Iterate over keys:
<syntaxhighlight lang="java">for (String key : map)
<syntaxhighlight lang="java">for (String key : map) {
{
// the variable "key" is defined here
// the variable "key" is defined here
}</syntaxhighlight>
}</syntaxhighlight>
Iterate over values:
Iterate over values:
<syntaxhighlight lang="java">for (Int value : map.values)
<syntaxhighlight lang="java">for (Int value : map.values) {
{
// the variable "value" is defined here
// the variable "value" is defined here
}</syntaxhighlight>
}</syntaxhighlight>
Iterate over key, value pairs:
Iterate over key, value pairs:
<syntaxhighlight lang="java">for ((String key, Int value) : map)
<syntaxhighlight lang="java">for ((String key, Int value) : map) {
{
// the variables "key" and "value" are defined here
// the variables "key" and "value" are defined here
}</syntaxhighlight>
}</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==