LinkedHashMap<K, V> abstract final#
An insertion-ordered Map with expected constant-time lookup.
A non-constant map literal, like {"a": 42, "b": 7}, is a LinkedHashMap.
The keys, values and entries are iterated in key insertion order.
The map uses a hash-table to look up entries, so keys must have suitable implementations of Object.operator== and Object.hashCode. If the hash codes are not well-distributed, the performance of map operations may suffer.
The insertion order of keys is remembered, and keys are iterated in the order they were inserted into the map. Values and entries are iterated in their corresponding key's order. Changing a key's value, when the key is already in the map, does not change the iteration order, but removing the key and adding it again will make it be last in the iteration order.
Notice: Do not modify a map (add or remove keys) while an operation is being performed on that map, for example in functions called during a forEach or putIfAbsent call, or while iterating the map (keys, values or entries).
The keys of a LinkedHashMap must have consistent Object.==
and Object.hashCode
implementations. This means that the == operator
must define a stable equivalence relation on the keys (reflexive,
symmetric, transitive, and consistent over time), and that hashCode
must be the same for objects that are considered equal by ==.
Example:
final planetsByDiameter = {0.949: 'Venus'}; // A new LinkedHashMap
To add data to a map, use operator[]=, addAll or addEntries.
planetsByDiameter[1] = 'Earth';
planetsByDiameter.addAll({0.532: 'Mars', 11.209: 'Jupiter'});
To check if the map is empty, use isEmpty or isNotEmpty. To find the number of map entries, use length.
print(planetsByDiameter.isEmpty); // false
print(planetsByDiameter.length); // 4
print(planetsByDiameter);
// {0.949: Venus, 1.0: Earth, 0.532: Mars, 11.209: Jupiter}
The forEach method calls a function for each key/value entry of the map.
planetsByDiameter.forEach((key, value) {
print('$key \t $value');
// 0.949 Venus
// 1.0 Earth
// 0.532 Mars
// 11.209 Jupiter
});
To check whether the map has an entry with a specific key, use containsKey.
final keyOneExists = planetsByDiameter.containsKey(1); // true
final keyFiveExists = planetsByDiameter.containsKey(5); // false
To check whether the map has an entry with a specific value, use containsValue.
final earthExists = planetsByDiameter.containsValue('Earth'); // true
final saturnExists = planetsByDiameter.containsValue('Saturn'); // false
To remove an entry with a specific key, use remove.
final removedValue = planetsByDiameter.remove(1);
print(removedValue); // Earth
print(planetsByDiameter); // {0.949: Venus, 0.532: Mars, 11.209: Jupiter}
To remove multiple entries at the same time, based on their keys and values, use removeWhere.
planetsByDiameter.removeWhere((key, value) => key == 0.949);
print(planetsByDiameter); // {0.532: Mars, 11.209: Jupiter}
To conditionally add or modify a value for a specific key, depending on whether there already is an entry with that key, use putIfAbsent or update.
planetsByDiameter.update(0.949, (v) => 'Venus', ifAbsent: () => 'Venus');
planetsByDiameter.putIfAbsent(0.532, () => "Another Mars if needed");
print(planetsByDiameter); // {0.532: Mars, 11.209: Jupiter, 0.949: Venus}
To update the values of all keys, based on the existing key and value, use updateAll.
planetsByDiameter.updateAll((key, value) => 'X');
print(planetsByDiameter); // {0.532: X, 11.209: X, 0.949: X}
To remove all entries and empty the map, use clear.
planetsByDiameter.clear();
print(planetsByDiameter); // {}
print(planetsByDiameter.isEmpty); // true
See also:
- Map, the general interface of key/value pair collections.
- HashMap is unordered (the order of iteration is not guaranteed).
- SplayTreeMap iterates the keys in sorted order.
Implemented types
Constructors#
LinkedHashMap() factory#
Creates an insertion-ordered hash-table based Map.
If equals is provided, it is used to compare the keys in the table with
new keys. If equals is omitted, the key's own Object.==
is used
instead.
The equals function must not change the map it's used as an equality
for. If it does, the resulting behavior is unspecified.
Similarly, if hashCode is provided, it is used to produce a hash value
for keys in order to place them in the hash table. If it is omitted, the
key's own Object.hashCode
is used.
The hashCode function must not change the map it's used as a hash code
for. If it does, the resulting behavior is unspecified.
The used equals and hashCode methods should always be consistent,
so that if equals(a, b) then hashCode(a) == hashCode(b). The hash
of an object, or what it compares equal to, should not change while the
object is in the table. If the hash code or equality of an object does
change, the resulting behavior is unspecified.
If you supply one of equals or hashCode,
you should generally also supply the other.
Some equals or hashCode functions might not work for all objects.
If isValidKey is supplied, it's used to check a potential key
which is not necessarily an instance of K, like the arguments to
operator [],
remove and containsKey, which are typed as
Object?.
If isValidKey returns false, for an object, the equals
and
hashCode functions are not called, and no key equal to that object
is assumed to be in the map.
The isValidKey function defaults to just testing if the object is an
instance of K.
Example:
LikedHashMap<int,int>(equals: (int a, int b) => (b - a) % 5 == 0,
hashCode: (int e) => e % 5)
This example map does not need an isValidKey function to be passed.
The default function accepts precisely int values, which can safely be
passed to both the equals and hashCode functions.
If neither equals, hashCode, nor isValidKey is provided,
the default isValidKey instead accepts all keys.
The default equality and hashcode operations are assumed to work on all
objects.
Likewise, if equals is identical,
hashCode is identityHashCode
and isValidKey is omitted, the resulting map is identity based,
and the isValidKey defaults to accepting all keys.
Such a map can be created directly using LinkedHashMap.identity.
Implementation
external factory LinkedHashMap({
bool Function(K, K)? equals,
int Function(K)? hashCode,
bool Function(dynamic)? isValidKey,
});
LinkedHashMap.from() factory#
Creates a LinkedHashMap
that contains all key value pairs of other.
The keys must all be instances of K and the values to V.
The other map itself can have any type.
Example:
final baseMap = <num, Object>{1: 'A', 2: 'B', 3: 'C'};
final fromBaseMap = LinkedHashMap<int, String>.from(baseMap);
print(fromBaseMap); // {1: A, 2: B, 3: C}
Implementation
factory LinkedHashMap.from(Map<dynamic, dynamic> other) {
LinkedHashMap<K, V> result = LinkedHashMap<K, V>();
other.forEach((dynamic k, dynamic v) {
result[k as K] = v as V;
});
return result;
}
LinkedHashMap.fromEntries() factory#
Creates a LinkedHashMap
containing the entries of entries.
Returns a new LinkedHashMap<K, V> where all entries of entries
have been added in iteration order.
If multiple entries have the same key,
later occurrences overwrite the earlier ones.
Example:
final numbers = [11, 12, 13, 14];
final map = LinkedHashMap.fromEntries(numbers.map((i) => MapEntry(i, i * i)));
print(map); // {11: 121, 12: 144, 13: 169, 14: 196}
Implementation
factory LinkedHashMap.fromEntries(Iterable<MapEntry<K, V>> entries) =>
LinkedHashMap<K, V>()..addEntries(entries);
LinkedHashMap.fromIterable() factory#
Creates a LinkedHashMap
where the keys and values are computed from the
iterable.
For each element of the iterable, this constructor computes a key/value
pair by applying key and value respectively.
The keys of the key/value pairs do not need to be unique. The last occurrence of a key will simply overwrite any previous value.
If no values are specified for key and value, the default is the
both default to the identity function.
Example:
final numbers = [11, 12, 13, 14];
final mapFromIterable =
LinkedHashMap.fromIterable(numbers, key: (i) => i, value: (i) => i * i);
print(mapFromIterable); // {11: 121, 12: 144, 13: 169, 14: 196}
Implementation
factory LinkedHashMap.fromIterable(
Iterable iterable, {
K Function(dynamic element)? key,
V Function(dynamic element)? value,
}) {
LinkedHashMap<K, V> map = LinkedHashMap<K, V>();
MapBase._fillMapWithMappedIterable(map, iterable, key, value);
return map;
}
LinkedHashMap.fromIterables() factory#
Creates a LinkedHashMap
associating the given keys to values.
This constructor iterates over keys and values and maps each element of
keys to the corresponding element of values.
If keys contains the same object multiple times, the last occurrence
overwrites the previous value.
It is an error if the two Iterables don't have the same length. Example:
final values = [0.06, 0.81, 1, 0.11];
final keys = ['Mercury', 'Venus', 'Earth', 'Mars'];
final mapFromIterables = LinkedHashMap.fromIterables(keys, values);
print(mapFromIterables);
// {Mercury: 0.06, Venus: 0.81, Earth: 1, Mars: 0.11}
Implementation
factory LinkedHashMap.fromIterables(Iterable<K> keys, Iterable<V> values) {
LinkedHashMap<K, V> map = LinkedHashMap<K, V>();
MapBase._fillMapWithIterables(map, keys, values);
return map;
}
LinkedHashMap.identity() factory#
Creates an insertion-ordered identity-based map.
Effectively shorthand for:
LinkedHashMap<K, V>(equals: identical,
hashCode: identityHashCode)
Implementation
external factory LinkedHashMap.identity();
LinkedHashMap.of() factory#
Creates a LinkedHashMap
that contains all key value pairs of other.
Example:
final baseMap = <int, String>{3: 'A', 2: 'B', 1: 'C', 4: 'D'};
final mapOf = LinkedHashMap<num, Object>.of(baseMap);
print(mapOf); // {3: A, 2: B, 1: C, 4: D}
Implementation
factory LinkedHashMap.of(Map<K, V> other) =>
LinkedHashMap<K, V>()..addAll(other);
Properties#
entries no setter inherited#
The map entries of this Map.
Inherited from Map.
Implementation
Iterable<MapEntry<K, V>> get entries;
hashCode no setter inherited#
The hash code for this object.
A hash code is a single integer which represents the state of the object that affects operator == comparisons.
All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).
If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.
Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.
Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.
If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.
Inherited from Object.
Implementation
external int get hashCode;
isEmpty no setter inherited#
Whether there is no key/value pair in the map.
Inherited from Map.
Implementation
bool get isEmpty;
isNotEmpty no setter inherited#
Whether there is at least one key/value pair in the map.
Inherited from Map.
Implementation
bool get isNotEmpty;
keys no setter inherited#
The keys of this Map.
The returned iterable has efficient length and contains operations,
based on length
and containsKey of the map.
The order of iteration is defined by the individual Map implementation,
but must be consistent between changes to the map.
Modifying the map while iterating the keys may break the iteration.
Inherited from Map.
Implementation
Iterable<K> get keys;
length no setter inherited#
The number of key/value pairs in the map.
Inherited from Map.
Implementation
int get length;
runtimeType no setter inherited#
A representation of the runtime type of the object.
Inherited from Object.
Implementation
external Type get runtimeType;
values no setter inherited#
The values of this Map.
The values are iterated in the order of their corresponding keys. This means that iterating keys and values in parallel will provide matching pairs of keys and values.
The returned iterable has an efficient length method based on the
length
of the map. Its Iterable.contains
method is based on
== comparison.
Modifying the map while iterating the values may break the iteration.
Inherited from Map.
Implementation
Iterable<V> get values;
Methods#
addAll() inherited#
Adds all key/value pairs of other to this map.
If a key of other is already in this map, its value is overwritten.
The operation is equivalent to doing this[key] = value for each key
and associated value in other. It iterates over other, which must
therefore not change during the iteration.
final planets = <int, String>{1: 'Mercury', 2: 'Earth'};
planets.addAll({5: 'Jupiter', 6: 'Saturn'});
print(planets); // {1: Mercury, 2: Earth, 5: Jupiter, 6: Saturn}
Inherited from Map.
Implementation
void addAll(Map<K, V> other);
addEntries() inherited#
Adds all key/value pairs of newEntries to this map.
If a key of newEntries is already in this map,
the corresponding value is overwritten.
The operation is equivalent to doing this[entry.key] = entry.value
for each MapEntry
of the iterable.
final planets = <int, String>{1: 'Mercury', 2: 'Venus',
3: 'Earth', 4: 'Mars'};
final gasGiants = <int, String>{5: 'Jupiter', 6: 'Saturn'};
final iceGiants = <int, String>{7: 'Uranus', 8: 'Neptune'};
planets.addEntries(gasGiants.entries);
planets.addEntries(iceGiants.entries);
print(planets);
// {1: Mercury, 2: Venus, 3: Earth, 4: Mars, 5: Jupiter, 6: Saturn,
// 7: Uranus, 8: Neptune}
Inherited from Map.
Implementation
void addEntries(Iterable<MapEntry<K, V>> newEntries);
cast() inherited#
Provides a view of this map as having RK keys and RV instances,
if necessary.
If this map is already a Map<RK, RV>, it is returned unchanged.
If this set contains only keys of type RK and values of type RV,
all read operations will work correctly.
If any operation exposes a non-RK key or non-RV value,
the operation will throw instead.
Entries added to the map must be valid for both a Map<K, V> and a
Map<RK, RV>.
Methods which accept Object? as argument,
like containsKey,
remove and operator [],
will pass the argument directly to the this map's method
without any checks.
That means that you can do mapWithStringKeys.cast<int,int>().remove("a")
successfully, even if it looks like it shouldn't have any effect.
Inherited from Map.
Implementation
Map<RK, RV> cast<RK, RV>();
clear() inherited#
Removes all entries from the map.
After this, the map is empty.
final planets = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
planets.clear(); // {}
Inherited from Map.
Implementation
void clear();
containsKey() inherited#
Whether this map contains the given key.
Returns true if any of the keys in the map are equal to key
according to the equality used by the map.
final moonCount = <String, int>{'Mercury': 0, 'Venus': 0, 'Earth': 1,
'Mars': 2, 'Jupiter': 79, 'Saturn': 82, 'Uranus': 27, 'Neptune': 14};
final containsUranus = moonCount.containsKey('Uranus'); // true
final containsPluto = moonCount.containsKey('Pluto'); // false
Inherited from Map.
Implementation
bool containsKey(Object? key);
containsValue() inherited#
Whether this map contains the given value.
Returns true if any of the values in the map are equal to value
according to the == operator.
final moonCount = <String, int>{'Mercury': 0, 'Venus': 0, 'Earth': 1,
'Mars': 2, 'Jupiter': 79, 'Saturn': 82, 'Uranus': 27, 'Neptune': 14};
final moons3 = moonCount.containsValue(3); // false
final moons82 = moonCount.containsValue(82); // true
Inherited from Map.
Implementation
bool containsValue(Object? value);
forEach() inherited#
Applies action to each key/value pair of the map.
Calling action must not add or remove keys from the map.
final planetsByMass = <num, String>{0.81: 'Venus', 1: 'Earth',
0.11: 'Mars', 17.15: 'Neptune'};
planetsByMass.forEach((key, value) {
print('$key: $value');
// 0.81: Venus
// 1: Earth
// 0.11: Mars
// 17.15: Neptune
});
Inherited from Map.
Implementation
void forEach(void action(K key, V value));
map() inherited#
Returns a new map where all entries of this map are transformed by
the given convert function.
Inherited from Map.
Implementation
Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> convert(K key, V value));
noSuchMethod() inherited#
Invoked when a nonexistent method or property is accessed.
A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:
dynamic object = 1;
object.add(42); // Statically allowed, run-time error
This invalid code will invoke the noSuchMethod method
of the integer 1 with an Invocation
representing the
.add(42) call and arguments (which then throws).
Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.
A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:
class MockList<T> implements List<T> {
noSuchMethod(Invocation invocation) {
log(invocation);
super.noSuchMethod(invocation); // Will throw.
}
}
void main() {
MockList().add(42);
}
This code has no compile-time warnings or errors even though
the MockList class has no concrete implementation of
any of the List interface methods.
Calls to List methods are forwarded to noSuchMethod,
so this code will log an invocation similar to
Invocation.method(#add, [42])
and then throw.
If a value is returned from noSuchMethod,
it becomes the result of the original invocation.
If the value is not of a type that can be returned by the original
invocation, a type error occurs at the invocation.
The default behavior is to throw a NoSuchMethodError.
Inherited from Object.
Implementation
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);
putIfAbsent() inherited#
Look up the value of key, or add a new entry if it isn't there.
Returns the value associated to key, if there is one.
Otherwise calls ifAbsent to get a new value, associates key
to
that value, and then returns the new value.
That is, if the key is currently in the map,
map.putIfAbsent(key, ifAbsent) is equivalent to map[key].
If the key is not currently in the map,
it's instead equivalent to map[key] = ifAbsent()
(but without any guarantee that the [] and []= operators are
actually called to achieve that effect).
final diameters = <num, String>{1.0: 'Earth'};
final otherDiameters = <double, String>{0.383: 'Mercury', 0.949: 'Venus'};
for (final item in otherDiameters.entries) {
diameters.putIfAbsent(item.key, () => item.value);
}
print(diameters); // {1.0: Earth, 0.383: Mercury, 0.949: Venus}
// If the key already exists, the current value is returned.
final result = diameters.putIfAbsent(0.383, () => 'Random');
print(result); // Mercury
print(diameters); // {1.0: Earth, 0.383: Mercury, 0.949: Venus}
The ifAbsent function is allowed to modify the map,
and if so, it behaves the same as the equivalent map[key] = ifAbsent().
Inherited from Map.
Implementation
V putIfAbsent(K key, V ifAbsent());
remove() inherited#
Removes key and its associated value, if present, from the map.
Returns the value associated with key before it was removed.
Returns null if key was not in the map.
Note that some maps allow null as a value,
so a returned null value doesn't always mean that the key was absent.
final terrestrial = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
final removedValue = terrestrial.remove(2); // Venus
print(terrestrial); // {1: Mercury, 3: Earth}
Inherited from Map.
Implementation
V? remove(Object? key);
removeWhere() inherited#
Removes all entries of this map that satisfy the given test.
final terrestrial = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
terrestrial.removeWhere((key, value) => value.startsWith('E'));
print(terrestrial); // {1: Mercury, 2: Venus}
Inherited from Map.
Implementation
void removeWhere(bool test(K key, V value));
toString() inherited#
A string representation of this object.
Some classes have a default textual representation,
often paired with a static parse function (like int.parse).
These classes will provide the textual representation as
their string representation.
Other classes have no meaningful textual representation
that a program will care about.
Such classes will typically override toString to provide
useful information when inspecting the object,
mainly for debugging or logging.
Inherited from Object.
Implementation
external String toString();
update() inherited#
Updates the value for the provided key.
Returns the new value associated with the key.
If the key is present, invokes update with the current value
and stores the new value in the map.
If the key is not present and ifAbsent is provided, calls ifAbsent
and adds the key with the returned value to the map.
If the key is not present, ifAbsent must be provided.
final planetsFromSun = <int, String>{1: 'Mercury', 2: 'unknown',
3: 'Earth'};
// Update value for known key value 2.
planetsFromSun.update(2, (value) => 'Venus');
print(planetsFromSun); // {1: Mercury, 2: Venus, 3: Earth}
final largestPlanets = <int, String>{1: 'Jupiter', 2: 'Saturn',
3: 'Neptune'};
// Key value 8 is missing from list, add it using [ifAbsent].
largestPlanets.update(8, (value) => 'New', ifAbsent: () => 'Mercury');
print(largestPlanets); // {1: Jupiter, 2: Saturn, 3: Neptune, 8: Mercury}
Inherited from Map.
Implementation
V update(K key, V update(V value), {V ifAbsent()?});
updateAll() inherited#
Updates all values.
Iterates over all entries in the map and updates them with the result
of invoking update.
final terrestrial = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
terrestrial.updateAll((key, value) => value.toUpperCase());
print(terrestrial); // {1: MERCURY, 2: VENUS, 3: EARTH}
Inherited from Map.
Implementation
void updateAll(V update(K key, V value));
Operators#
operator ==() inherited#
The equality operator.
The default behavior for all Objects is to return true if and
only if this object and other are the same object.
Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:
Total: It must return a boolean for all arguments. It should never throw.
Reflexive: For all objects
o,o == omust be true.-
Symmetric: For all objects
o1ando2,o1 == o2ando2 == o1must either both be true, or both be false. -
Transitive: For all objects
o1,o2, ando3, ifo1 == o2ando2 == o3are true, theno1 == o3must be true.
The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.
If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.
Inherited from Object.
Implementation
external bool operator ==(Object other);
operator []() inherited#
The value for the given key, or null if key is not in the map.
Some maps allow null as a value.
For those maps, a lookup using this operator cannot distinguish between a
key not being in the map, and the key being there with a null value.
Methods like containsKey
or putIfAbsent can be used if the distinction
is important.
Inherited from Map.
Implementation
V? operator [](Object? key);
operator []=() inherited#
Associates the key with the given value.
If the key was already in the map, its associated value is changed. Otherwise the key/value pair is added to the map.
Inherited from Map.
Implementation
void operator []=(K key, V value);