ListMap<K, V>.fromEntries constructor
ListMap<K, V>.fromEntries (})
Creates a ListMap from entries
.
If entries
contains the same keys multiple times, the last occurrence
overwrites the previous value.
If sort
is true, the entries will be sorted with compare
,
if provided, or with compareObject if not provided. If sort
is false, compare
will be ignored.
Implementation
factory ListMap.fromEntries(
Iterable<MapEntry<K, V>> entries, {
bool sort = false,
int Function(K a, K b)? compare,
}) {
assert(compare == null || sort == true);
Map<K, V> map;
List<K> list;
// Sorted:
if (sort) {
map = HashMap<K, V>();
for (final MapEntry<K, V> entry in entries) {
map[entry.key] = entry.value;
}
list = map.entries.map((entry) => entry.key).toList(growable: false);
list.sort(compare ?? compareObject);
}
// Insertion order:
else {
// First create a map in insertion order, removing duplicate keys.
map = LinkedHashMap<K, V>.fromEntries(entries);
// Then create the list in the insertion order.
list = map.entries.map((entry) => entry.key).toList(growable: false);
// Remove the linked-list from the map (by using a HashMap).
map = HashMap.of(map);
}
return ListMap._(map, list);
}