Associative array/Creation: Difference between revisions

 
(9 intermediate revisions by 7 users not shown)
Line 2,749:
# typed (coerces to float)</syntaxhighlight>
=={{header|EasyLang}}==
<syntaxhighlight>
EasyLang does not really have associative arrays, but arrays of arrays type is a good substitute.
# use array of array for this
<syntaxhighlight lang="easylang">
proc hashGet ind$ . ar$[][] item$ .
associative$[][] = [ [ 1 "associative" ] [ 2 "arrays" ] ]
for i to len ar$[][]
</syntaxhighlight>
if ar$[i][1] = ind$
And here are functions for indexing associative arrays:
item$ = ar$[i][2]
<syntaxhighlight lang="easylang">
return
func indexAssoc index . array[][] item .
for i = 1 to len array[][]
if array[i][1] = index
item = array[i][2]
break 2
.
.
item$ = number "nan"
.
funcproc indexStrAssochashSet indexind$ val$ . arrayar$[][] item$ .
for i = 1 to len arrayar$[][]
if arrayar$[i][1] = indexind$
item$ = arrayar$[i][2] = val$
break 2return
.
.
item$ = ""
.
clothing$[][] = [ [ "type" "t-shirt" ] [ "color" "red" ] ]
clothing$[][] &= [ "size" "xl" ]
#
hashSet "color" "green" clothing$[][]
hashGet "color" clothing$[][] col$
print col$
</syntaxhighlight>
 
Line 2,809 ⟶ 2,810:
<syntaxhighlight lang="java">Int? mightBeNull = map["foo"];
Int neverNull = map.getOrDefault("foo", 0);
if (Int n := map.get("foo")) {
{
// 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
}</syntaxhighlight>
Iterate over keys:
<syntaxhighlight lang="java">for (String key : map) {
{
// the variable "key" is defined here
}</syntaxhighlight>
Iterate over values:
<syntaxhighlight lang="java">for (Int value : map.values) {
{
// the variable "value" is defined here
}</syntaxhighlight>
Iterate over key, value pairs:
<syntaxhighlight lang="java">for ((String key, Int value) : map) {
{
// the variables "key" and "value" are defined here
}</syntaxhighlight>
 
=={{header|Elena}}==
Line 3,445 ⟶ 3,440:
say "'baz' => [V].";
end the story.</syntaxhighlight>
 
=={{header|Insitux}}==
 
It is possible to use any value type for both keys and values for a dictionary in Insitux.
 
<syntaxhighlight lang="insitux">{
:a "value" ;keyword key, string value
:b 123 ;keyword key, number value
456 [1 2 3] ;number key, vector value
[5 6 7] :b ;vector key, keyword value
{:a 1} {:b 2} ;dictionary key, dictionary value
}</syntaxhighlight>
 
<syntaxhighlight lang="insitux">;use dictionary as function for lookup; commas for readability, treated as white-space
> ({:a 1, :b 2, :c 3} :b)
2</syntaxhighlight>
 
<syntaxhighlight lang="insitux">;extend existing dictionary by using it as a function with two arguments
> ({:a 1, :b 2, :c 3} :b 3)
{:a 1, :b 3, :c 3}</syntaxhighlight>
 
=={{header|Ioke}}==
Line 3,479 ⟶ 3,494:
Note that J's symbols (http://www.jsoftware.com/help/dictionary/dsco.htm) might also be used for this purpose. However, symbols are not garbage collected within a J session (and, instead, a mechanism is provided to optionally preserve them across sessions).
 
=={{header|JavaJakt}}==
<syntaxhighlight lang="jakt">
{{works with|Java|1.5+}}
fn main() {
 
let dictionary = ["foo": 1, "bar": 2]
Defining the Map:
println("{}", dictionary)
<syntaxhighlight lang="java5">Map<String, Integer> map = new HashMap<String, Integer>();
}
map.put("foo", 5);
</syntaxhighlight>
map.put("bar", 10);
map.put("baz", 15);
map.put("foo", 6);</syntaxhighlight>
"Putting" a value for a key that already exists ("map.put("foo", 6)" in this example) will replace and return the old value for the key.
 
=={{header|Java}}==
Initializing a Map as a class member:
<p>
<syntaxhighlight lang="java5">public static Map<String, Integer> map = new HashMap<String, Integer>(){{
Java offers an associative array, referred to as a <code>Map</code>, as part of the Collections Framework.<br />
put("foo", 5);
There are numerous implementing classes, each which provide unique functionality for various tasks.<br />
put("bar", 10);
</p>
put("baz", 15);
<p>
put("foo", 6);
It's worth noting that Java also offers the <code>Dictionary</code> class, which appears to be less preferred, according to Java.<br />
}};</syntaxhighlight>
<kbd><i>"[The Map] interface takes the place of the Dictionary class ..."</i></kbd>.
Retrieving a value:
</p>
<syntaxhighlight lang="java5">map.get("foo"); // => 6
<p>
map.get("invalid"); // => null</syntaxhighlight>
Note that it is possibleThe tomost putgeneralized <code>nullMap</code> aswould abe value, sothe <code>nullHashMap</code>, being returned by <code>get</code>which is nota sufficientbasic, forunordered, determiningset that the key is not in theof <codekbd>Mapkeys</codekbd>. There is aand <codekbd>containsKeyvalues</codekbd> method for that.<br />
There is also the <code>LinkedHashMap</code>, which will preserve the order of input.<br />
 
There is the <code>TreeMap</code>, which is used to store the <kbd>key</kbd>s in a specific order, using the <kbd>key</kbd>'s <code>compareTo</code> method.
Iterate over keys:
Optionally, you could provide your own <kbd>comparator</kbd> using the <code>Comparator</code> interface, which I'll demonstrate below.<br />
<syntaxhighlight lang="java5">for (String key: map.keySet())
There are numerous other implementing classes, which can be found under the <code>Map</code> <kbd>Javadoc</kbd>,
System.out.println(key);</syntaxhighlight>
[https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/Map.html. Map (Java SE 20 & JDK 20)].
Iterate over values:
</p>
<syntaxhighlight lang="java5">for (int value: map.values())
<p>
System.out.println(value);</syntaxhighlight>
Here is a basic implementation of a <code>HashMap</code>.
Iterate over key, value pairs:
</p>
<syntaxhighlight lang="java5">for (Map.Entry<String, Integer> entry: map.entrySet())
<syntaxhighlight lang="java">
System.out.println(entry.getKey() + " => " + entry.getValue());</syntaxhighlight>
Map<String, Integer> map = new HashMap<>();
</syntaxhighlight>
<p>
To add a <kbd>key</kbd> and <kbd>value</kbd> pair, you use the <code>Map.put</code> method.<br />
A useful feature of <code>Map.put</code> is that if the <kbd>key</kbd> already exists, thus is being overridden,
it will return the overridden value, otherwise <code>null</code>.
</p>
<syntaxhighlight lang="java">
map.put("rosetta", 100);
map.put("code", 200);
</syntaxhighlight>
<p>
To get a <kbd>value</kbd>, you use the <code>Map.get</code> method, specifying the <kbd>key</kbd> as the parameter.<br />
If the specified <kbd>key</kbd> does not exist, <code>null</code> is returned.
</p>
<syntaxhighlight lang="java">
int valueA = map.get("rosetta");
int valueB = map.get("code");
</syntaxhighlight>
<p>
To mutate a <kbd>key</kbd>'s <kbd>value</kbd>, you use the <code>Map.replace</code> method.
</p>
<syntaxhighlight lang="java">
map.replace("rosetta", 300);
</syntaxhighlight>
<p>
Alternately, you can replace the <kbd>value</kbd>, only if it is of a current <kbd>value</kbd>.<br />
So, in this example it will return <kbd>true</kbd>, only if the <kbd>key</kbd> <kbd><i>"rosetta"</i></kbd> had the current <kbd>value</kbd> of <kbd><i>100</i></kbd>.
</p>
<syntaxhighlight lang="java">
boolean replaced = map.replace("rosetta", 100, 300);
</syntaxhighlight>
<p>
To check for the existence of a <kbd>key</kbd>, you use the <code>containsKey</code> method.
</p>
<syntaxhighlight lang="java">
boolean contains = map.containsKey("rosetta");
</syntaxhighlight>
<p>
And to check for the existence of a <kbd>value</kbd>, you use the <code>containsValue</code> method.
</p>
<syntaxhighlight lang="java">
boolean contains = map.containsValue(100);
</syntaxhighlight>
<p>
A <code>LinkedHashMap</code> is exactly the same as a <code>HashMap</code>, except it will preserve the order in which the <kbd>key</kbd>s were added.
</p>
<syntaxhighlight lang="java">
Map<String, Integer> map = new LinkedHashMap<>();
map.put("rosetta", 100);
map.put("code", 200);
</syntaxhighlight>
<p>
A <code>TreeMap</code> is useful for when you want the <kbd>key</kbd>s in a specific order.<br />
By default, it will use the <kbd>key</kbd>'s <code>compareTo</code> method, to determine the order.<br />
So, if you're <kbd>key</kbd> is a <code>String</code>, the order will be ascending, similar to an actual dictionary.
</p>
<syntaxhighlight lang="java">
Map<String, Integer> map = new TreeMap<>();
map.put("rosetta", 100);
map.put("code", 200);
</syntaxhighlight>
<p>
You could, optionally, specify a comparator by implementing a <code>Comparator</code> interface.<br />
A <code>TreeMap</code>, conveniently, only requires you to implement the <code>compare</code> method of the <code>Comparator</code>,
so the implementation can be done as an <kbd>anonymous class</kbd>.
</p>
<syntaxhighlight lang="java">
Comparator<String> comparator = new Comparator<String>() {
public int compare(String stringA, String stringB) {
if (stringA.compareTo(stringB) > 0) {
return -1;
} else if (stringA.compareTo(stringB) < 0) {
return 1;
}
return 0;
}
};
</syntaxhighlight>
<p>
Which you then supply as an argument to the constructor.
</p>
<syntaxhighlight lang="java">
Map<String, Integer> map = new TreeMap<>(comparator);
</syntaxhighlight>
<p>
To make things even simpler, you could use a <kbd>lambda</kbd> for the <kbd>anonymous class</kbd>.
</p>
<syntaxhighlight lang="java">
Comparator<String> comparator = (stringA, stringB) -> {
if (stringA.compareTo(stringB) > 0) {
return -1;
} else if (stringA.compareTo(stringB) < 0) {
return 1;
}
return 0;
};
</syntaxhighlight>
 
=={{header|JavaScript}}==
Line 3,823 ⟶ 3,933:
Hash keys in langur may be numbers or strings. Number keys are simplified, so that 1.0 is the same key as 1.
 
<syntaxhighlight lang="langur">var .hash = h{1: "abc", "1": 789}
 
# may assign with existing or non-existing hash key (if hash is mutable)
Line 5,925 ⟶ 6,035:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var hash = Hash.new(
key1 => 'value1',
key2 => 'value2',
);
 
# Add a new key-value pair
hash{:key3} = 'value3';</syntaxhighlight>
 
=={{header|Slate}}==
Line 6,309 ⟶ 6,419:
=={{header|Wren}}==
Wren has a Map class built in.
<syntaxhighlight lang="ecmascriptwren">var fruit = {} // creates an empty map
fruit[1] = "orange" // associates a key of 1 with "orange"
fruit[2] = "apple" // associates a key of 2 with "apple"
Line 6,338 ⟶ 6,448:
null
</pre>
 
 
=={{header|XLISP}}==
885

edits