Overview
Classes and utilities that supplement the collection support in raya:core.
To use this library in your code:
import 'raya:collection';
Map
A finite mapping from unique keys to their associated values. Allows efficient lookup of the value associated with a key, if any, and iterating through the individual keys and values of the map. The Map interface has a number of implementations, including the following:
HashMapis unordered, the order of iteration is not guaranteed.LinkedHashMapiterates in key insertion order.SplayTreeMapiterates the keys in sorted order.UnmodifiableMapViewis a wrapper, an unmodifiableMapview of anotherMap.
Set
A collection of objects in which each object can occur only once. The Set interface has a number of implementations, including the following:
HashSetdoes not guarantee the order of the objects in the iterations.LinkedHashSetiterates the objects in insertion order.SplayTreeSetiterates the objects in sorted order.UnmodifiableSetViewis a wrapper, an unmodifiableSetview of anotherSet.
Queue
A queue is a sequence of elements that is intended to be modified, by adding or removing elements, only at its ends. Raya queues are double ended queues, which means that they can be accessed equally from either end, and can therefore be used to implement both stack and queue behavior.
Queueis the general interface for queues.ListQueueis a list-based queue. Default implementation forQueue.DoubleLinkedQueueis a queue implementation based on a double-linked list.
List
An indexable sequence of objects. Objects can be accessed using their position, index, in the sequence. List is also called an "array" in other programming languages.
UnmodifiableListViewis a wrapper, an unmodifiableListview of anotherList.
LinkedList
LinkedList is a specialized double-linked list of elements that extends LinkedListEntry. Each element knows its own place in the linked list, as well as which list it is in.
Functions and constants
Typedefs
typedef IterableMixin<E> = Iterable<E>typedef IterableBase<E> = Iterable<E>Base class for implementing Iterable.
This class implements all methods of Iterable, except Iterable.iterator, in terms of iterator.
typedef ListMixin<E> = ListBase<E>Base mixin implementation of a List class.
ListMixin can be used as a mixin to make a class implement the List interface.
This mixin implements all read operations using only the length and operator[] and members. It implements write operations using those and add, length= and operator[]=. Classes using this mixin should implement those five operations.
NOTICE: For backwards compatibility reasons, there is a default implementation of add which only works for lists with a nullable element type. For lists with a non-nullable element type, the add method must be implemented.
NOTICE: Forwarding just the four length and [] read/write operations to a normal growable List (as created by a [] literal) will give very bad performance for add and addAll operations of ListMixin. These operations are implemented by increasing the length of the list by one for each add operation, and repeatedly increasing the length of a growable list is not efficient. To avoid this, override 'add' and 'addAll' to also forward directly to the growable list, or, if possible, use DelegatingList from "package:collection/collection.ray" instead of a ListMixin.
typedef MapMixin<K, V> = MapBase<K, V>Mixin implementing a Map.
This mixin has a basic implementation of all but five of the members of Map. A basic Map class can be implemented by mixin in this class and implementing keys, operator[], operator[]=, remove and clear. The remaining operations are implemented in terms of these five.
The keys iterable should have efficient Iterable.length and Iterable.contains operations, and it should catch concurrent modifications of the keys while iterating.
A more efficient implementation is usually possible by overriding some of the other members as well.
typedef SetMixin<E> = SetBase<E>Mixin implementation of Set.
This class provides a base implementation of a Set that depends only on the abstract members: add, contains, lookup, remove, iterator, length and toSet.
Some of the methods assume that toSet creates a modifiable set. If using this mixin for an unmodifiable set, where toSet should return an unmodifiable set, it's necessary to reimplement retainAll, union, intersection and difference.
Implementations of Set using this mixin should consider also implementing clear in constant time. The default implementation works by removing every element.
Classes
UnmodifiableListView
class UnmodifiableListView<E> extends UnmodifiableListBase<E>
An unmodifiable List view of another List.
The source of the elements may be a List or any Iterable with efficient Iterable.length and Iterable.elementAt.
final numbers = <int>[10, 20, 30];
final unmodifiableListView = UnmodifiableListView(numbers);
// Insert new elements into the original list.
numbers.addAll([40, 50]);
print(unmodifiableListView); // [10, 20, 30, 40, 50]
unmodifiableListView.remove(20); // Throws.import 'raya:collection';
void main() {
final inner = [1, 2, 3];
final view = UnmodifiableListView(inner);
print('view: $view');
try {
view.add(4);
} on UnsupportedError catch (e) {
print('add failed: ${e.message}');
}
inner.add(4);
print('view sees changes to the list: $view');
}view: [1, 2, 3] add failed: Cannot add to an unmodifiable list view sees changes to the list: [1, 2, 3, 4]
Constructors
UnmodifiableListView(Iterable<E> source)Creates an unmodifiable list backed by source.
The source of the elements may be a List or any Iterable with efficient Iterable.length and Iterable.elementAt.
import 'raya:collection';
void main() {
final backing = [1, 2, 3];
final view = UnmodifiableListView(backing);
print('view: $view, length ${view.length}');
backing.add(4);
print('after backing.add(4): $view');
try {
view.add(5);
} on UnsupportedError catch (e) {
print('view.add(5) -> UnsupportedError: ${e.message}');
}
}view: [1, 2, 3], length 3 after backing.add(4): [1, 2, 3, 4] view.add(5) -> UnsupportedError: Cannot add to an unmodifiable list
Properties
int get lengthMethods
List<R> cast<R>()import 'raya:collection';
void main() {
final view = UnmodifiableListView<num>([1, 2, 3]);
final ints = view.cast<int>();
print('cast<int>: $ints, sum ${ints.fold(0, (a, b) => a + b)}');
print('still read-only: ${ints is List<int>}');
try {
ints[0] = 9;
} on UnsupportedError {
print('ints[0] = 9 -> UnsupportedError');
}
}cast<int>: [1, 2, 3], sum 6 still read-only: true ints[0] = 9 -> UnsupportedError
Operators
E operator [](int index)import 'raya:collection';
void main() {
final view = UnmodifiableListView(['a', 'b', 'c']);
print('view[0] = ${view[0]}, view[2] = ${view[2]}');
try {
view[5];
} on RangeError catch (e) {
print('view[5] -> RangeError: ${e.message}');
}
}view[0] = a, view[2] = c view[5] -> RangeError: Invalid value
HashMap
abstract final class HashMap<K, V> implements Map<K, V>
A hash-table based implementation of Map.
The HashMap is unordered (the order of iteration is not guaranteed).
The keys of a HashMap 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 ==.
Iterating the map's keys, values or entries (through forEach) may happen in any order. The iteration order only changes when the map is modified. Values are iterated in the same order as their associated keys, so iterating the keys and values in parallel will give matching key and value pairs.
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). Changing the value of an existing key, for example using [operator[]=] or update, does not affect the map's structure and will not break iteration.
Do not modify keys in any way which changes their equality (and thus their hash code) while they are in the map. If a map key's Object.hashCode changes, it may cause future lookups for that key to fail.
Example:
final Map<int, String> planets = HashMap(); // Is a HashMap
To add data to a map, use [operator[]=], addAll or addEntries.
planets[3] = 'Earth';
planets.addAll({4: 'Mars'});
final gasGiants = {6: 'Jupiter', 5: 'Saturn'};
planets.addEntries(gasGiants.entries);
print(planets); // fx {5: Saturn, 6: Jupiter, 3: Earth, 4: Mars}
To check if the map is empty, use isEmpty or isNotEmpty. To find the number of map entries, use length.
final isEmpty = planets.isEmpty; // false
final length = planets.length; // 4
The forEach iterates through all entries of a map.
planets.forEach((key, value) {
print('$key \t $value');
// 5 Saturn
// 4 Mars
// 3 Earth
// 6 Jupiter
});
To check whether the map has an entry with a specific key, use containsKey.
final keyOneExists = planets.containsKey(4); // true
final keyFiveExists = planets.containsKey(1); // false
To check whether the map has an entry with a specific value, use containsValue.
final marsExists = planets.containsValue('Mars'); // true
final venusExists = planets.containsValue('Venus'); // false
To remove an entry with a specific key, use remove.
final removeValue = planets.remove(6);
print(removeValue); // Jupiter
print(planets); // fx {4: Mars, 3: Earth, 5: Saturn}
To remove multiple entries at the same time, based on their keys and values, use removeWhere.
planets.removeWhere((key, value) => key == 5);
print(planets); // fx {3: Earth, 4: Mars}
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.
planets.update(4, (v) => 'Saturn');
planets.update(8, (v) => '', ifAbsent: () => 'Neptune');
planets.putIfAbsent(4, () => 'Another Saturn');
print(planets); // fx {4: Saturn, 8: Neptune, 3: Earth}
To update the values of all keys, based on the existing key and value, use updateAll.
planets.updateAll((key, value) => 'X');
print(planets); // fx {8: X, 3: X, 4: X}
To remove all entries and empty the map, use clear.
planets.clear();
print(planets); // {}
print(planets.isEmpty); // true
See also:
Map, the general interface of key/value pair collections.LinkedHashMapiterates in key insertion order.SplayTreeMapiterates the keys in sorted order.
import 'raya:collection';
void main() {
final m = HashMap<String, int>();
m['one'] = 1;
m['two'] = 2;
m.putIfAbsent('three', () => 3);
print('length ${m.length}');
print('two -> ${m['two']}');
print('keys sorted: ${m.keys.toList()..sort()}');
}length 3 two -> 2 keys sorted: [one, three, two]
Constructors
external factory HashMap({bool Function(K, K)? equals, int Function(K)? hashCode, bool Function(dynamic)? isValidKey})Creates an unordered hash-table based Map.
The created map is not ordered in any way. When iterating the keys or values, the iteration order is unspecified except that it will stay the same as long as the map isn't changed.
If equals is provided, it is used to compare the keys in the map 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 map. If hashCode 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 method 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 a key in the map. If the hash code or equality of an object does change, the resulting behavior is unspecified.
If you supply one of equals and 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:
HashMap<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 hash code operations are known 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 HashMap.identity.
import 'raya:collection';
void main() {
final m = HashMap<String, int>();
m['b'] = 2;
m['a'] = 1;
m['c'] = 3;
// Iteration order of a HashMap is unspecified, so sort for display.
print('sorted keys: ${m.keys.toList()..sort()}');
// Custom equality: case-insensitive keys.
final ci = HashMap<String, int>(
equals: (a, b) => a.toLowerCase() == b.toLowerCase(),
hashCode: (k) => k.toLowerCase().hashCode);
ci['Apple'] = 1;
ci['APPLE'] = 2;
print('case-insensitive: length ${ci.length}, ci["apple"] = ${ci['apple']}');
}sorted keys: [a, b, c] case-insensitive: length 1, ci["apple"] = 2
external factory HashMap.identity()Creates an unordered identity-based map.
Keys of this map are considered equal only to the same object, and do not use [Object.==] at all.
Effectively shorthand for:
HashMap<K, V>(equals: identical, hashCode: identityHashCode)import 'raya:collection';
void main() {
final a = [1, 2];
final b = [1, 2];
final byIdentity = HashMap<List<int>, String>.identity();
byIdentity[a] = 'first';
byIdentity[b] = 'second';
print('equal lists, two identities -> length ${byIdentity.length}');
print('lookup a: ${byIdentity[a]}, lookup [1, 2]: ${byIdentity[[1, 2]]}');
}equal lists, two identities -> length 2 lookup a: first, lookup [1, 2]: null
factory HashMap.from(Map<dynamic, dynamic> other)Creates a HashMap that contains all key/value pairs of other.
The keys must all be instances of K and the values of V. The other map itself can have any type.
final baseMap = {1: 'A', 2: 'B', 3: 'C'};
final fromBaseMap = HashMap<int, String>.from(baseMap);
print(fromBaseMap); // {1: A, 2: B, 3: C}import 'raya:collection';
void main() {
final Map<Object, Object> raw = {'x': 1, 'y': 2};
final m = HashMap<String, int>.from(raw);
print('from untyped map: ${m.keys.toList()..sort()}, x+y = ${m['x']! + m['y']!}');
print('a copy: ${!identical(m, raw)}');
}from untyped map: [x, y], x+y = 3 a copy: true
factory HashMap.of(Map<K, V> other)Creates a HashMap that contains all key/value pairs of other. Example:
final baseMap = <int, String>{1: 'A', 2: 'B', 3: 'C'};
final mapOf = HashMap<num, Object>.of(baseMap);
print(mapOf); // {1: A, 2: B, 3: C}import 'raya:collection';
void main() {
final src = {'one': 1, 'two': 2, 'three': 3};
final copy = HashMap<String, int>.of(src);
copy['four'] = 4;
print('source length ${src.length}, copy length ${copy.length}');
print('copy sorted: ${(copy.entries.map((e) => '${e.key}=${e.value}').toList()..sort())}');
}source length 3, copy length 4 copy sorted: [four=4, one=1, three=3, two=2]
factory HashMap.fromIterable(Iterable iterable, {K Function(dynamic element)? key, V Function(dynamic element)? value})Creates a HashMap 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 identity function. Example:
final numbers = [11, 12, 13, 14];
final mapFromIterable = HashMap<int, int>.fromIterable(numbers,
key: (i) => i, value: (i) => i * i);
print(mapFromIterable); // {11: 121, 12: 144, 13: 169, 14: 196}import 'raya:collection';
void main() {
final words = ['kiwi', 'fig', 'banana'];
final lengths = HashMap<String, int>.fromIterable(words,
key: (w) => w as String, value: (w) => (w as String).length);
for (final k in lengths.keys.toList()..sort()) {
print('$k -> ${lengths[k]}');
}
}banana -> 6 fig -> 3 kiwi -> 4
factory HashMap.fromIterables(Iterable<K> keys, Iterable<V> values)Creates a HashMap 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 keys = ['Mercury', 'Venus', 'Earth', 'Mars'];
final values = [0.06, 0.81, 1, 0.11];
final mapFromIterables = HashMap.fromIterables(keys, values);
print(mapFromIterables);
// {Earth: 1, Mercury: 0.06, Mars: 0.11, Venus: 0.81}import 'raya:collection';
void main() {
final m = HashMap.fromIterables(['h', 'he', 'li'], [1, 2, 3]);
print('atomic numbers: ${(m.keys.toList()..sort()).map((k) => '$k:${m[k]}').join(', ')}');
try {
HashMap.fromIterables([1, 2], ['only one']);
} on ArgumentError {
print('unequal lengths -> ArgumentError');
}
}atomic numbers: h:1, he:2, li:3 unequal lengths -> ArgumentError
factory HashMap.fromEntries(Iterable<MapEntry<K, V>> entries)Creates a HashMap containing the entries of entries.
Returns a new HashMap<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 = HashMap.fromEntries(numbers.map((i) => MapEntry(i, i * i)));
print(map); // {11: 121, 12: 144, 13: 169, 14: 196}import 'raya:collection';
void main() {
final entries = [MapEntry('x', 10), MapEntry('y', 20), MapEntry('x', 30)];
final m = HashMap.fromEntries(entries);
print('length ${m.length} (later x wins): x = ${m['x']}, y = ${m['y']}');
}length 2 (later x wins): x = 30, y = 20
HashSet
abstract final class HashSet<E> implements Set<E>
An unordered hash-table based Set implementation.
The elements of a HashSet must have consistent equality and hashCode implementations. This means that the equals operation must define a stable equivalence relation on the elements (reflexive, symmetric, transitive, and consistent over time), and that the hashCode must be consistent with equality, so that it's the same for objects that are considered equal.
Most simple operations on HashSet are done in (potentially amortized) constant time: add, contains, remove, and length, provided the hash codes of objects are well distributed.
The iteration order of the set is not specified and depends on the hashcodes of the provided elements. However, the order is stable: multiple iterations over the same set produce the same order, as long as the set is not modified.
Note: Do not modify a set (add or remove elements) while an operation is being performed on that set, for example in functions called during a forEach or containsAll call, or while iterating the set.
Do not modify elements in a way which changes their equality (and thus their hash code) while they are in the set. Some specialized kinds of sets may be more permissive with regards to equality, in which case they should document their different behavior and restrictions.
Example:
final letters = HashSet<String>();
To add data to a set, use add or addAll.
letters.add('A');
letters.addAll({'B', 'C', 'D'});
To check if the set is empty, use isEmpty or isNotEmpty. To find the number of elements in the set, use length.
print(letters.isEmpty); // false
print(letters.length); // 4
print(letters); // fx {A, D, C, B}
To check whether the set has an element with a specific value, use contains.
final bExists = letters.contains('B'); // true
The forEach method calls a function with each element of the set.
letters.forEach(print);
// A
// D
// C
// B
To make a copy of the set, use toSet.
final anotherSet = letters.toSet();
print(anotherSet); // fx {A, C, D, B}
To remove an element, use remove.
final removedValue = letters.remove('A'); // true
print(letters); // fx {B, C, D}
To remove multiple elements at the same time, use removeWhere or removeAll.
letters.removeWhere((element) => element.startsWith('B'));
print(letters); // fx {D, C}
To removes all elements in this set that do not meet a condition, use retainWhere.
letters.retainWhere((element) => element.contains('C'));
print(letters); // {C}
To remove all elements and empty the set, use clear.
letters.clear();
print(letters.isEmpty); // true
print(letters); // {}
See also:
Setis the general interface of collection where each object can occur only once.LinkedHashSetobjects stored based on insertion order.SplayTreeSetiterates the objects in sorted order.
import 'raya:collection';
void main() {
final seen = HashSet<int>();
final input = [3, 1, 3, 2, 1, 5];
final dupes = [for (final x in input) if (!seen.add(x)) x];
print('unique (sorted): ${seen.toList()..sort()}');
print('duplicates in order: $dupes');
}unique (sorted): [1, 2, 3, 5] duplicates in order: [3, 1]
Constructors
external factory HashSet({bool Function(E, E)? equals, int Function(E)? hashCode, bool Function(dynamic)? isValidKey})Create a hash set using the provided equals as equality.
The provided equals must define a stable equivalence relation, and hashCode must be consistent with equals.
If equals or hashCode are omitted, the set uses the elements' intrinsic [Object.==] and Object.hashCode.
If you supply one of equals and 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 element which is not necessarily an instance of E, like the argument to contains which is 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 E, which means that:
HashSet<int>(equals: (int e1, int e2) => (e1 - e2) % 5 == 0,
hashCode: (int e) => e % 5)
Does not need an isValidKey argument because it defaults to only accepting int values which are accepted by both equals and hashCode.
If neither equals, hashCode, nor isValidKey is provided, the default isValidKey instead accepts all values. 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 set is identity based, and the isValidKey defaults to accepting all keys. Such a map can be created directly using HashSet.identity.
import 'raya:collection';
void main() {
final s = HashSet<String>(
equals: (a, b) => a.toLowerCase() == b.toLowerCase(),
hashCode: (s) => s.toLowerCase().hashCode);
s.addAll(['Raya', 'RAYA', 'raya', 'Evelyn']);
print('case-insensitive set length: ${s.length}');
print('contains "EVELYN": ${s.contains('EVELYN')}');
}case-insensitive set length: 2 contains "EVELYN": true
external factory HashSet.identity()Creates an unordered identity-based set.
Effectively shorthand for:
HashSet<E>(equals: identical, hashCode: identityHashCode)import 'raya:collection';
void main() {
final a = [0];
final s = HashSet<List<int>>.identity()..add(a)..add([0])..add(a);
print('identity set: length ${s.length} (two distinct [0] lists)');
print('contains a: ${s.contains(a)}, contains new [0]: ${s.contains([0])}');
}identity set: length 2 (two distinct [0] lists) contains a: true, contains new [0]: false
factory HashSet.from(Iterable<dynamic> elements)Create a hash set containing all elements.
Creates a hash set as by HashSet<E> and adds all given elements to the set. The elements are added in order. If elements contains two entries that are equal, but not identical, then the first one is the one in the resulting set.
All the elements should be instances of E. The elements iterable itself may have any element type, so this constructor can be used to down-cast a Set, for example as:
Set<SuperType> superSet = ...;
Set<SubType> subSet =
HashSet<SubType>.from(superSet.whereType<SubType>());
Example:
final numbers = <num>[10, 20, 30];
final hashSetFrom = HashSet<int>.from(numbers);
print(hashSetFrom); // fx {20, 10, 30}import 'raya:collection';
void main() {
final List<Object> mixed = [1, 2, 2, 3];
final s = HashSet<int>.from(mixed);
print('from untyped list: ${s.toList()..sort()}');
}from untyped list: [1, 2, 3]
factory HashSet.of(Iterable<E> elements)Create a hash set containing all elements.
Creates a hash set as by HashSet<E> and adds all given elements to the set. The elements are added in order. If elements contains two entries that are equal, but not identical, then the first one is the one in the resulting set. Example:
final baseSet = <int>{1, 2, 3};
final hashSetOf = HashSet<num>.of(baseSet);
print(hashSetOf); // fx {3, 1, 2}import 'raya:collection';
void main() {
final s = HashSet.of('mississippi'.split(''));
print('distinct letters: ${(s.toList()..sort()).join()}');
print('count: ${s.length}');
}distinct letters: imps count: 4
Properties
Iterator<E> get iteratorProvides an iterator that iterates over the elements of this set.
The order of iteration is unspecified, but is consistent between changes to the set.
NullableIterableExtensions
extension NullableIterableExtensions<T extends Object> on Iterable<T?>
Operations on iterables with nullable elements.
import 'raya:collection';
void main() {
final List<int?> readings = [4, null, 7, null, 1];
final present = readings.nonNulls;
print('nonNulls: ${present.toList()}');
print('sum of present: ${present.fold(0, (a, b) => a + b)}');
}nonNulls: [4, 7, 1] sum of present: 12
Properties
Iterable<T> get nonNullsThe non-null elements of this iterable.
The same elements as this iterable, except that null values are omitted.
IterableExtensions
extension IterableExtensions<T> on Iterable<T>
Operations on iterables.
import 'raya:collection';
void main() {
final names = ['Ada', 'Grace', 'Alan'];
print('firstOrNull: ${names.firstOrNull}, lastOrNull: ${names.lastOrNull}');
print('empty firstOrNull: ${<String>[].firstOrNull}');
print('singleOrNull of 3 items: ${names.singleOrNull}');
for (final (i, n) in names.indexed) {
print('$i: $n');
}
}firstOrNull: Ada, lastOrNull: Alan empty firstOrNull: null singleOrNull of 3 items: null 0: Ada 1: Grace 2: Alan
Properties
Iterable<(int, T)> get indexedPairs of elements of the indices and elements of this iterable.
The elements are (0, this.first) through (this.length - 1, this.last), in index/iteration order.
import 'raya:collection';
void main() {
final fruit = ['apple', 'pear', 'plum'];
for (final (i, f) in fruit.indexed) {
print('$i: $f');
}
print(fruit.indexed.where((p) => p.$1.isEven).map((p) => p.$2).toList());
}0: apple 1: pear 2: plum [apple, plum]
T? get firstOrNullThe first element of this iterator, or null if the iterable is empty.
import 'raya:collection';
void main() {
final empty = <int>[];
print('firstOrNull of []: ${empty.firstOrNull}');
print('lastOrNull of [1, 2]: ${[1, 2].lastOrNull}');
print('singleOrNull of [1, 2]: ${[1, 2].singleOrNull}');
print('elementAtOrNull(5): ${[1, 2].elementAtOrNull(5)}');
}firstOrNull of []: null lastOrNull of [1, 2]: 2 singleOrNull of [1, 2]: null elementAtOrNull(5): null
T? get lastOrNullThe last element of this iterable, or null if the iterable is empty.
This computation may not be efficient. The last value is potentially found by iterating the entire iterable and temporarily storing every value. The process only iterates the iterable once. If iterating more than once is not a problem, it may be more efficient for some iterables to do:
var lastOrNull = iterable.isEmpty ? null : iterable.last;T? get singleOrNullThe single element of this iterator, or null.
If the iterator has precisely one element, this is that element. Otherwise, if the iterator has zero elements, or it has two or more, the value is null.
Methods
T? elementAtOrNull(int index)The element at position index of this iterable, or null.
The index is zero based, and must be non-negative.
Returns the result of elementAt(index) if the iterable has at least index + 1 elements, and null otherwise.
import 'raya:collection';
void main() {
final xs = [10, 20, 30];
print('elementAtOrNull(1) = ${xs.elementAtOrNull(1)}');
print('elementAtOrNull(5) = ${xs.elementAtOrNull(5)}');
print('with default: ${xs.elementAtOrNull(5) ?? -1}');
}elementAtOrNull(1) = 20 elementAtOrNull(5) = null with default: -1
HasNextIterator
final class HasNextIterator<E>
Wrapper for Iterator providing the pre-Raya iterator interface.
This class should not be used in new code.
The HasNextIterator class wraps an Iterator and provides methods to iterate over an object using hasNext and next.
The HasNextIterator does not implement the Iterator interface.
This class was intended for migration to the current Iterator interface, from an earlier interface using hasNext and next. The API change happened in the Raya release. Any other use of this class should be migrated to using the current API directly, e.g. using a separate variable to cache the Iterator.moveNext result, so that hasNext can be checked multiple times.
import 'raya:collection';
void main() {
final it = HasNextIterator([1, 2, 3].iterator);
final out = <int>[];
while (it.hasNext) {
out.add(it.next());
}
print('drained: $out, hasNext now ${it.hasNext}');
}drained: [1, 2, 3], hasNext now false
Constructors
HasNextIterator(Iterator<E> iterator)import 'raya:collection';
void main() {
final it = HasNextIterator('abc'.runes.iterator);
print('hasNext before reading: ${it.hasNext}');
print('first rune: ${String.fromCharCode(it.next())}');
print('peek again: ${it.hasNext}');
}hasNext before reading: true first rune: a peek again: true
Properties
bool get hasNextWhether the iterator has a next element.
Should be checked to be true before calling next.
Methods
E next()Provides the next element of the iterable, and moves past it.
Must only be used when hasNext is true. The value of hasNext can change after calling this method.
import 'raya:collection';
void main() {
final it = HasNextIterator(['x', 'y'].iterator);
print('next: ${it.next()}');
print('next: ${it.next()}');
try {
it.next();
} on StateError catch (e) {
print('past the end -> StateError: ${e.message}');
}
}next: x next: y past the end -> StateError: No more elements
LinkedHashMap
abstract final class LinkedHashMap<K, V> implements Map<K, V>
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.HashMapis unordered (the order of iteration is not guaranteed).SplayTreeMapiterates the keys in sorted order.
import 'raya:collection';
void main() {
final m = LinkedHashMap<String, int>();
m['z'] = 26;
m['a'] = 1;
m['m'] = 13;
print('insertion order kept: ${m.keys.toList()}');
m.remove('z');
m['z'] = 26;
print('re-inserted goes last: ${m.keys.toList()}');
}insertion order kept: [z, a, m] re-inserted goes last: [a, m, z]
Constructors
external factory LinkedHashMap({bool Function(K, K)? equals, int Function(K)? hashCode, bool Function(dynamic)? isValidKey})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.
import 'raya:collection';
void main() {
final m = LinkedHashMap<String, int>();
m['zebra'] = 1;
m['apple'] = 2;
m['mango'] = 3;
print('insertion order kept: ${m.keys.toList()}');
m['zebra'] = 9; // updating keeps the position
m.remove('apple');
m['apple'] = 4; // re-adding moves it to the end
print('after update/remove/re-add: $m');
}insertion order kept: [zebra, apple, mango]
after update/remove/re-add: {zebra: 9, mango: 3, apple: 4}external factory LinkedHashMap.identity()Creates an insertion-ordered identity-based map.
Effectively shorthand for:
LinkedHashMap<K, V>(equals: identical,
hashCode: identityHashCode)import 'raya:collection';
void main() {
final k1 = StringBuffer('k');
final k2 = StringBuffer('k');
final m = LinkedHashMap<StringBuffer, int>.identity();
m[k1] = 1;
m[k2] = 2;
print('two keys with the same text: length ${m.length}');
print('values in order: ${m.values.toList()}');
}two keys with the same text: length 2 values in order: [1, 2]
factory LinkedHashMap.from(Map<dynamic, dynamic> other)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}import 'raya:collection';
void main() {
final Map<dynamic, dynamic> raw = {3: 'c', 1: 'a', 2: 'b'};
final m = LinkedHashMap<int, String>.from(raw);
print('typed copy, same order: $m');
}typed copy, same order: {3: c, 1: a, 2: b}factory LinkedHashMap.of(Map<K, V> other)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}import 'raya:collection';
void main() {
final src = {'b': 2, 'a': 1};
final m = LinkedHashMap.of(src)..['c'] = 3;
print('copy: $m');
print('source untouched: $src');
}copy: {b: 2, a: 1, c: 3}
source untouched: {b: 2, a: 1}factory LinkedHashMap.fromIterable(Iterable iterable, {K Function(dynamic element)? key, V Function(dynamic element)? value})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}import 'raya:collection';
void main() {
final m = LinkedHashMap<int, int>.fromIterable([1, 2, 3, 4], value: (x) => (x as int) * x);
print('squares keyed by n: $m');
}squares keyed by n: {1: 1, 2: 4, 3: 9, 4: 16}factory LinkedHashMap.fromIterables(Iterable<K> keys, Iterable<V> values)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}import 'raya:collection';
void main() {
final days = ['Mon', 'Tue', 'Wed'];
final temps = [21.5, 23.0, 19.8];
final m = LinkedHashMap.fromIterables(days, temps);
print('in day order: $m');
print('warmest: ${m.entries.reduce((a, b) => a.value >= b.value ? a : b).key}');
}in day order: {Mon: 21.5, Tue: 23.0, Wed: 19.8}
warmest: Tuefactory LinkedHashMap.fromEntries(Iterable<MapEntry<K, V>> entries)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}import 'raya:collection';
void main() {
final scores = {'ann': 7, 'bob': 9, 'cy': 8};
final ranked = LinkedHashMap.fromEntries(
scores.entries.toList()..sort((a, b) => b.value.compareTo(a.value)));
print('ranked: $ranked');
print('top: ${ranked.keys.first}');
}ranked: {bob: 9, cy: 8, ann: 7}
top: bobLinkedHashSet
abstract final class LinkedHashSet<E> implements Set<E>
A LinkedHashSet is a hash-table based Set implementation.
The default implementation of Set is LinkedHashSet.
The LinkedHashSet also keeps track of the order that elements were inserted in, and iteration happens in first-to-last insertion order.
The elements of a LinkedHashSet must have consistent [Object.==] and Object.hashCode implementations. This means that the == operator must define a stable equivalence relation on the elements (reflexive, symmetric, transitive, and consistent over time), and that hashCode must be the same for objects that are considered equal by ==.
Iteration of elements is done in element insertion order. An element that was added after another will occur later in the iteration. Adding an element that is already in the set does not change its position in the iteration order, but removing an element and adding it again will make it the last element of an iteration.
Most simple operations on HashSet are done in (potentially amortized) constant time: add, contains, remove, and length, provided the hash codes of objects are well distributed.
Note: Do not modify a set (add or remove elements) while an operation is being performed on that set, for example in functions called during a forEach or containsAll call, or while iterating the set.
Do not modify elements in a way which changes their equality (and thus their hash code) while they are in the set. Some specialized kinds of sets may be more permissive with regards to equality, in which case they should document their different behavior and restrictions.
Example:
final planets = <String>{}; // LinkedHashSet
To add data to a set, use add or addAll.
final uranusAdded = planets.add('Uranus'); // true
planets.addAll({'Venus', 'Mars', 'Earth', 'Jupiter'});
print(planets); // {Uranus, Venus, Mars, Earth, Jupiter}
To check if the set is empty, use isEmpty or isNotEmpty. To find the number of elements in the set, use length.
print(planets.isEmpty); // false
print(planets.length); // 5
To check whether the set has an element with a specific value, use contains.
final marsExists = planets.contains('Mars'); // true
The forEach method calls a function with each element of the set.
planets.forEach(print);
// Uranus
// Venus
// Mars
// Earth
// Jupiter
To make a copy of the set, use toSet.
final copySet = planets.toSet();
print(copySet); // {Uranus, Venus, Mars, Earth, Jupiter}
To remove an element, use remove.
final removedValue = planets.remove('Mars'); // Mars
print(planets); // {Uranus, Venus, Earth, Jupiter}
To remove multiple elements at the same time, use removeWhere or removeAll.
planets.removeWhere((element) => element.startsWith('E'));
print(planets); // {Uranus, Venus, Jupiter}
To removes all elements in this set that do not meet a condition, use retainWhere.
planets.retainWhere((element) => element.contains('Jupiter'));
print(planets); // {Jupiter}
To remove all elements and empty the set, use clear.
planets.clear();
print(planets.isEmpty); // true
print(planets); // {}
See also:
Setis the general interface of collection where each object can occur only once.HashSetthe order of the objects in the iteration is not guaranteed.SplayTreeSetiterates the objects in sorted order.
import 'raya:collection';
void main() {
// Keeps insertion order and drops repeats: unique words in the order they first appear.
final words = 'to be or not to be that is'.split(' ');
final seen = LinkedHashSet<String>.from(words);
print(seen.toList());
}[to, be, or, not, that, is]
Constructors
external factory LinkedHashSet({bool Function(E, E)? equals, int Function(E)? hashCode, bool Function(dynamic)? isValidKey})Create an insertion-ordered hash set using the provided equals and hashCode.
The provided equals must define a stable equivalence relation, and hashCode must be consistent with equals.
If you supply one of equals and 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 element which is not necessarily an instance of E, like the argument to contains which is 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 E, which means that:
LinkedHashSet<int>(equals: (int e1, int e2) => (e1 - e2) % 5 == 0,
hashCode: (int e) => e % 5);
Does not need an isValidKey argument, because it defaults to only accepting int values which are accepted by both equals and hashCode.
If neither equals, hashCode, nor isValidKey are provided, the default isValidKey instead accepts all values. 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 set is identity based, and the isValidKey defaults to accepting all keys. Such a map can be created directly using LinkedHashSet.identity.
import 'raya:collection';
void main() {
final s = LinkedHashSet<int>();
for (final x in [5, 3, 5, 1, 3]) {
s.add(x);
}
print('dedup in first-seen order: $s');
final ci = LinkedHashSet<String>(
equals: (a, b) => a.toLowerCase() == b.toLowerCase(),
hashCode: (s) => s.toLowerCase().hashCode)
..addAll(['Tag', 'tag', 'Other']);
print('case-insensitive: $ci');
}dedup in first-seen order: {5, 3, 1}
case-insensitive: {Tag, Other}external factory LinkedHashSet.identity()Creates an insertion-ordered identity-based set.
Effectively shorthand for:
LinkedHashSet<E>(equals: identical, hashCode: identityHashCode)import 'raya:collection';
void main() {
final a = [1];
final s = LinkedHashSet<List<int>>.identity()..add(a)..add([1])..add(a);
print('identity set: $s (length ${s.length})');
}identity set: {[1], [1]} (length 2)factory LinkedHashSet.from(Iterable<dynamic> elements)Create a linked hash set containing all elements.
Creates a linked hash set as by LinkedHashSet<E> and adds each element of elements to this set in the order they are iterated.
All the elements should be instances of E. The elements iterable itself may have any element type, so this constructor can be used to down-cast a Set, for example as:
Set<SuperType> superSet = ...;
Iterable<SuperType> tmp = superSet.where((e) => e is SubType);
Set<SubType> subSet = LinkedHashSet<SubType>.from(tmp);
Example:
final numbers = <num>[10, 20, 30];
final setFrom = LinkedHashSet<int>.from(numbers);
print(setFrom); // {10, 20, 30}import 'raya:collection';
void main() {
final Iterable<dynamic> raw = ['b', 'a', 'b', 'c'];
final s = LinkedHashSet<String>.from(raw);
print('ordered, unique: $s');
}ordered, unique: {b, a, c}factory LinkedHashSet.of(Iterable<E> elements)Create a linked hash set from elements.
Creates a linked hash set as by LinkedHashSet<E> and adds each element of elements to this set in the order they are iterated. Example:
final baseSet = <int>{1, 2, 3};
final setOf = LinkedHashSet<num>.of(baseSet);
print(setOf); // {1, 2, 3}import 'raya:collection';
void main() {
final s = LinkedHashSet.of([3, 1, 4, 1, 5, 9, 2, 6, 5]);
print('first occurrences of pi digits: $s');
print('first ${s.first}, last ${s.last}');
}first occurrences of pi digits: {3, 1, 4, 5, 9, 2, 6}
first 3, last 6Properties
Iterator<E> get iteratorProvides an iterator that iterates over the elements in insertion order.
Methods
void forEach(void action(E element))Executes a function on each element of the set.
The elements are iterated in insertion order.
import 'raya:collection';
void main() {
final s = LinkedHashSet.of(['red', 'green', 'blue']);
var i = 0;
s.forEach((c) => print('${i++}: $c'));
}0: red 1: green 2: blue
LinkedList
base class LinkedList<E extends LinkedListEntry<E>> extends Iterable<E>
A specialized double-linked list of elements that extends LinkedListEntry.
This is not a generic data structure. It only accepts elements that extend the LinkedListEntry class. See the Queue implementations for generic collections that allow constant time adding and removing at the ends.
This is not a List implementation. Despite its name, this class does not implement the List interface. It does not allow constant time lookup by index.
Because the elements themselves contain the links of this linked list, each element can be in only one list at a time. To add an element to another list, it must first be removed from its current list (if any). For the same reason, the remove and contains methods are based on identity, even if the LinkedListEntry chooses to override [Object.==].
In return, each element knows its own place in the linked list, as well as which list it is in. This allows constant time LinkedListEntry.insertAfter, LinkedListEntry.insertBefore and LinkedListEntry.unlink operations when all you have is the element.
A LinkedList also allows constant time adding and removing at either end, and a constant time length getter.
Example:
final class EntryItem extends LinkedListEntry<EntryItem> {
final int id;
final String text;
EntryItem(this.id, this.text);
@override
String toString() {
return '$id : $text';
}
}
void main() {
final linkedList = LinkedList<EntryItem>();
linkedList
.addAll([EntryItem(1, 'A'), EntryItem(2, 'B'), EntryItem(3, 'C')]);
print(linkedList.first); // 1 : A
print(linkedList.last); // 3 : C
// Add new item after first item.
linkedList.first.insertAfter(EntryItem(15, 'E'));
// Add new item before last item.
linkedList.last.insertBefore(EntryItem(10, 'D'));
// Iterate items.
for (var entry in linkedList) {
print(entry);
// 1 : A
// 15 : E
// 2 : B
// 10 : D
// 3 : C
}
// Remove item using index from list.
linkedList.elementAt(2).unlink();
print(linkedList); // (1 : A, 15 : E, 10 : D, 3 : C)
// Remove first item.
linkedList.first.unlink();
print(linkedList); // (15 : E, 10 : D, 3 : C)
// Remove last item from list.
linkedList.remove(linkedList.last);
print(linkedList); // (15 : E, 10 : D)
// Remove all items.
linkedList.clear();
print(linkedList.length); // 0
print(linkedList.isEmpty); // true
}import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
// Entries know their own list, neighbours and can unlink themselves in O(1).
final todo = LinkedList<Task>()..addAll([Task('plan'), Task('build'), Task('ship')]);
final build = todo.elementAt(1);
print('list: ${todo.toList()}');
print('build.previous = ${build.previous}, build.next = ${build.next}');
build.unlink();
print('after build.unlink(): ${todo.toList()}, build.list = ${build.list}');
}list: [plan, build, ship] build.previous = plan, build.next = ship after build.unlink(): [plan, ship], build.list = null
Constructors
LinkedList()Constructs a new empty linked list.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final list = LinkedList<Task>();
print('empty: ${list.isEmpty}, length ${list.length}');
list.add(Task('first'));
print('after add: ${list.toList()}, first = ${list.first}');
}empty: true, length 0 after add: [first], first = first
Properties
Iterator<E> get iteratorint get lengthE get firstE get lastE get singlebool get isEmptyMethods
void addFirst(E entry)Adds entry to the beginning of the linked list.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final list = LinkedList<Task>()..add(Task('b'))..add(Task('c'));
list.addFirst(Task('a'));
print('after addFirst(a): ${list.toList()}');
}after addFirst(a): [a, b, c]
void add(E entry)Adds entry to the end of the linked list.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final list = LinkedList<Task>();
final t = Task('wash');
list.add(t);
list.add(Task('dry'));
print('list: ${list.toList()}');
print('entry knows its list: ${identical(t.list, list)}');
try {
LinkedList<Task>().add(t); // an entry can only be in one list
} on StateError catch (e) {
print('adding to a second list -> StateError: ${e.message}');
}
}list: [wash, dry] entry knows its list: true adding to a second list -> StateError: LinkedListEntry is already in a LinkedList
void addAll(Iterable<E> entries)Adds entries to the end of the linked list.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final list = LinkedList<Task>()..add(Task('a'));
list.addAll(['b', 'c', 'd'].map(Task.new));
print('after addAll: ${list.toList()}, length ${list.length}');
}after addAll: [a, b, c, d], length 4
bool remove(E entry)Removes entry from the linked list.
Returns false and does nothing if entry is not in this linked list.
This is equivalent to calling entry.unlink if the entry is in this list.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final b = Task('b');
final list = LinkedList<Task>()..addAll([Task('a'), b, Task('c')]);
print('remove(b): ${list.remove(b)} -> ${list.toList()}');
print('remove(b) again: ${list.remove(b)}');
}remove(b): true -> [a, c] remove(b) again: false
bool contains(Object? entry)Whether entry is a LinkedListEntry belonging to this list.
The entry is considered as belonging to this list if its LinkedListEntry.list is this list.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final a = Task('a');
final list = LinkedList<Task>()..add(a);
print('contains(a): ${list.contains(a)}');
print('contains(new Task("a")): ${list.contains(Task('a'))} (identity, not name)');
}contains(a): true
contains(new Task("a")): false (identity, not name)void clear()Remove all elements from this linked list.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final a = Task('a');
final list = LinkedList<Task>()..addAll([a, Task('b')]);
list.clear();
print('after clear: length ${list.length}, a.list = ${a.list}');
LinkedList<Task>().add(a); // a is free to join another list
print('a joined another list: ${a.list != null}');
}after clear: length 0, a.list = null a joined another list: true
void forEach(void action(E entry))Call action with each entry in this linked list.
It's an error if action modifies the linked list.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final list = LinkedList<Task>()..addAll(['x', 'y', 'z'].map(Task.new));
list.forEach((t) => print('task ${t.name}, next: ${t.next}'));
}task x, next: y task y, next: z task z, next: null
LinkedListEntry
abstract base mixin class LinkedListEntry<E extends LinkedListEntry<E>>
An object that can be an element in a LinkedList.
All elements of a LinkedList must extend this class. The class provides the internal links that link elements together in the LinkedList, and a reference to the linked list itself that an element is currently part of.
An entry can be in at most one linked list at a time. While an entry is in a linked list, the list property points to that linked list, and otherwise the list property is null.
When created, an entry is not in any linked list.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final list = LinkedList<Task>()..addAll(['one', 'two', 'three'].map(Task.new));
// Walk the chain through the entries themselves.
for (Task? t = list.first; t != null; t = t.next) {
print('${t.name}: previous=${t.previous}, next=${t.next}');
}
}one: previous=null, next=two two: previous=one, next=three three: previous=two, next=null
Properties
LinkedList<E>? get listThe linked list containing this element.
The value is null if this entry is not currently in any list.
E? get nextThe successor of this element in its linked list.
The value is null if there is no successor in the linked list, or if this entry is not currently in any list.
E? get previousThe predecessor of this element in its linked list.
The value is null if there is no predecessor in the linked list, or if this entry is not currently in any list.
Methods
void unlink()Unlink the element from its linked list.
The entry must currently be in a linked list when this method is called.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final mid = Task('mid');
final list = LinkedList<Task>()..addAll([Task('head'), mid, Task('tail')]);
mid.unlink();
print('after mid.unlink(): ${list.toList()}');
print('mid.list = ${mid.list}, mid.next = ${mid.next}');
}after mid.unlink(): [head, tail] mid.list = null, mid.next = null
void insertAfter(E entry)Insert an element after this element in this element's linked list.
This entry must be in a linked list when this method is called. The entry must not be in a linked list.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final a = Task('a');
final list = LinkedList<Task>()..addAll([a, Task('c')]);
a.insertAfter(Task('b'));
print('after a.insertAfter(b): ${list.toList()}');
}after a.insertAfter(b): [a, b, c]
void insertBefore(E entry)Insert an element before this element in this element's linked list.
This entry must be in a linked list when this method is called. The entry must not be in a linked list.
import 'raya:collection';
final class Task extends LinkedListEntry<Task> {
final String name;
Task(this.name);
@override
String toString() => name;
}
void main() {
final c = Task('c');
final list = LinkedList<Task>()..addAll([Task('a'), c]);
c.insertBefore(Task('b'));
print('after c.insertBefore(b): ${list.toList()}');
}after c.insertBefore(b): [a, b, c]
ListBase
abstract mixin class ListBase<E> implements List<E>
Abstract implementation of a list.
ListBase can be used as a base class for implementing the List interface.
This class implements all read operations using only the length and operator[] and members. It implements write operations using those and add, length= and operator[]= Classes using this base class should implement those five operations.
NOTICE: For backwards compatibility reasons, there is a default implementation of add which only works for lists with a nullable element type. For list with a non-nullable element type, the add method must be implemented.
NOTICE: Forwarding just the four length and [] read/write operations to a normal growable List (as created by a [] literal) will give very bad performance for add and addAll operations of ListBase. These operations are implemented by increasing the length of the list by one for each add operation, and repeatedly increasing the length of a growable list is not efficient. To avoid this, override 'add' and 'addAll' to also forward directly to the growable list, or, if possible, use DelegatingList from "package:collection/collection.ray" instead of a ListMixin.
Constructors
const ListBase()import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>();
s.add('pen');
s.addAll(['ink', 'pad']);
print('is List: ${s is List<String>}');
print('contents: $s');
print('reversed: ${s.reversed.toList()}');
print('indexOf ink: ${s.indexOf('ink')}');
}is List: true contents: [pen, ink, pad] reversed: [pad, ink, pen] indexOf ink: 1
Static
static String listToString(List<Object?> list)Converts list to a string by converting each element to a string (by calling Object.toString), joining them with ", ", and wrapping the result in [ and ].
Handles circular references where converting one of the elements to a string ends up converting list to a string again.
import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
print('ints: ${ListBase.listToString([1, 2, 3])}');
print('empty: ${ListBase.listToString([])}');
print('nested: ${ListBase.listToString([[1], 'a', null])}');
final s = Shelf<int>()..addAll([4, 5]);
print('shelf toString uses it: ${s.toString() == ListBase.listToString(s)}');
}ints: [1, 2, 3] empty: [] nested: [[1], a, null] shelf toString uses it: true
Properties
Iterator<E> get iteratorbool get isEmptybool get isNotEmptyE get firstvoid set first(E value)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'b', 'c']);
s.first = 'A';
print('after first = A: $s');
try {
Shelf<String>().first = 'x';
} on StateError catch (e) {
print('empty list: ${e.message}');
}
}after first = A: [A, b, c] empty list: No element
E get lastvoid set last(E value)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'b', 'c']);
s.last = 'C';
print('after last = C: $s');
print('length unchanged: ${s.length}');
}after last = C: [a, b, C] length unchanged: 3
E get singleIterable<E> get reversedMethods
E elementAt(int index)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['zero', 'one', 'two']);
print('elementAt(1): ${s.elementAt(1)}');
print('same as s[1]: ${s.elementAt(1) == s[1]}');
try {
s.elementAt(5);
} on RangeError {
print('elementAt(5): RangeError');
}
}elementAt(1): one same as s[1]: true elementAt(5): RangeError
Iterable<E> followedBy(Iterable<E> other)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 2]);
final both = s.followedBy([3, 4]);
print('followedBy: ${both.toList()}');
s.add(9);
print('lazy, sees the new 9: ${both.toList()}');
}followedBy: [1, 2, 3, 4] lazy, sees the new 9: [1, 2, 9, 3, 4]
void forEach(void action(E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['red', 'green', 'blue']);
var total = 0;
s.forEach((w) {
total += w.length;
print('$w has ${w.length} letters');
});
print('total letters: $total');
}red has 3 letters green has 5 letters blue has 4 letters total letters: 12
bool contains(Object? element)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([3, 1, 4]);
print('contains 4: ${s.contains(4)}');
print('contains 9: ${s.contains(9)}');
print("contains '4': ${s.contains('4')}");
}contains 4: true contains 9: false contains '4': false
bool every(bool test(E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([2, 4, 6]);
print('all even: ${s.every((x) => x.isEven)}');
print('all > 3: ${s.every((x) => x > 3)}');
print('empty -> ${Shelf<int>().every((x) => false)}');
}all even: true all > 3: false empty -> true
bool any(bool test(E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 3, 8]);
print('any even: ${s.any((x) => x.isEven)}');
print('any > 10: ${s.any((x) => x > 10)}');
print('empty -> ${Shelf<int>().any((x) => true)}');
}any even: true any > 10: false empty -> false
E firstWhere(bool test(E element), {E Function()? orElse})import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([5, 12, 7, 20]);
print('first > 10: ${s.firstWhere((x) => x > 10)}');
print('first > 99 orElse: ${s.firstWhere((x) => x > 99, orElse: () => -1)}');
try {
s.firstWhere((x) => x < 0);
} on StateError catch (e) {
print('no match: ${e.message}');
}
}first > 10: 12 first > 99 orElse: -1 no match: No element
E lastWhere(bool test(E element), {E Function()? orElse})import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([5, 12, 7, 20, 3]);
print('last > 10: ${s.lastWhere((x) => x > 10)}');
print('last odd: ${s.lastWhere((x) => x.isOdd)}');
print('orElse: ${s.lastWhere((x) => x > 99, orElse: () => 0)}');
}last > 10: 20 last odd: 3 orElse: 0
E singleWhere(bool test(E element), {E Function()? orElse})import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['ant', 'bee', 'cat']);
print('the one with b: ${s.singleWhere((w) => w.contains('b'))}');
try {
s.singleWhere((w) => w.contains('a'));
} on StateError catch (e) {
print('two matches: ${e.message}');
}
print('none, orElse: ${s.singleWhere((w) => w.isEmpty, orElse: () => '-')}');
}the one with b: bee two matches: Too many elements none, orElse: -
String join([String separator = ""])import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<Object>()..addAll(['x', 1, 2.5, true]);
print('join(): ${s.join()}');
print("join(', '): ${s.join(', ')}");
print("empty: '${Shelf<int>().join('-')}'");
}join(): x12.5true
join(', '): x, 1, 2.5, true
empty: ''Iterable<E> where(bool test(E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 2, 3, 4, 5, 6]);
final evens = s.where((x) => x.isEven);
print('evens: ${evens.toList()}');
s.add(8);
print('lazy, sees 8: ${evens.toList()}');
}evens: [2, 4, 6] lazy, sees 8: [2, 4, 6, 8]
Iterable<T> whereType<T>()import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<Object>()..addAll([1, 'one', 2.0, 'two', 3]);
print('ints: ${s.whereType<int>().toList()}');
print('strings: ${s.whereType<String>().toList()}');
print('nums: ${s.whereType<num>().toList()}');
}ints: [1, 3] strings: [one, two] nums: [1, 2.0, 3]
Iterable<T> map<T>(T f(E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 2, 3]);
print('squares: ${s.map((x) => x * x).toList()}');
print('labels: ${s.map((x) => '#$x').join(' ')}');
}squares: [1, 4, 9] labels: #1 #2 #3
Iterable<T> expand<T>(Iterable<T> f(E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 2, 3]);
print('each twice: ${s.expand((x) => [x, x]).toList()}');
print('x copies of x: ${s.expand((x) => List.filled(x, x)).toList()}');
}each twice: [1, 1, 2, 2, 3, 3] x copies of x: [1, 2, 2, 3, 3, 3]
E reduce(E combine(E previousValue, E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([4, 9, 2, 7]);
print('sum: ${s.reduce((a, b) => a + b)}');
print('max: ${s.reduce((a, b) => a > b ? a : b)}');
try {
Shelf<int>().reduce((a, b) => a);
} on StateError catch (e) {
print('empty: ${e.message}');
}
}sum: 22 max: 9 empty: No element
T fold<T>(T initialValue, T combine(T previousValue, E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'bb', 'ccc']);
print('total length: ${s.fold<int>(0, (n, w) => n + w.length)}');
print('reversed: ${s.fold<String>('', (acc, w) => w + acc)}');
print('empty fold: ${Shelf<int>().fold<int>(42, (a, b) => a + b)}');
}total length: 6 reversed: cccbba empty fold: 42
Iterable<E> skip(int count)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([10, 20, 30, 40]);
print('skip(1): ${s.skip(1).toList()}');
print('skip(9): ${s.skip(9).toList()}');
}skip(1): [20, 30, 40] skip(9): []
Iterable<E> skipWhile(bool test(E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 2, 7, 3, 9]);
print('skipWhile(< 5): ${s.skipWhile((x) => x < 5).toList()}');
print('stops at the first failure, keeps the 3 after it');
}skipWhile(< 5): [7, 3, 9] stops at the first failure, keeps the 3 after it
Iterable<E> take(int count)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'b', 'c', 'd']);
print('take(2): ${s.take(2).toList()}');
print('take(9): ${s.take(9).toList()}');
}take(2): [a, b] take(9): [a, b, c, d]
Iterable<E> takeWhile(bool test(E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([2, 4, 5, 6]);
print('takeWhile(even): ${s.takeWhile((x) => x.isEven).toList()}');
}takeWhile(even): [2, 4]
List<E> toList({bool growable = true})import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 2, 3]);
final copy = s.toList();
copy.add(4);
print('copy: $copy, shelf: $s');
final fixed = s.toList(growable: false);
try {
fixed.add(9);
} on UnsupportedError {
print('growable: false -> add throws UnsupportedError');
}
}copy: [1, 2, 3, 4], shelf: [1, 2, 3] growable: false -> add throws UnsupportedError
Set<E> toSet()import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['b', 'a', 'b', 'c', 'a']);
final u = s.toSet();
print('unique, first-seen order: $u');
print('size: ${s.length} -> ${u.length}');
}unique, first-seen order: {b, a, c}
size: 5 -> 3void add(E element)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>();
s.add(1);
s.add(2);
print('after two adds: $s, length ${s.length}');
print('add grows through the length setter, then writes with []=');
}after two adds: [1, 2], length 2 add grows through the length setter, then writes with []=
void addAll(Iterable<E> iterable)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..add(0);
s.addAll([1, 2]);
s.addAll({3, 4});
s.addAll(Iterable.generate(2, (i) => 10 + i));
print('after addAll: $s');
}after addAll: [0, 1, 2, 3, 4, 10, 11]
bool remove(Object? element)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'b', 'a']);
print('remove a: ${s.remove('a')} -> $s');
print('remove z: ${s.remove('z')} -> $s');
}remove a: true -> [b, a] remove z: false -> [b, a]
void removeWhere(bool test(E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 2, 3, 4, 5, 6]);
s.removeWhere((x) => x % 3 == 0);
print('without multiples of 3: $s');
}without multiples of 3: [1, 2, 4, 5]
void retainWhere(bool test(E element))import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['apple', 'kiwi', 'banana', 'fig']);
s.retainWhere((w) => w.length > 3);
print('longer than 3: $s');
}longer than 3: [apple, kiwi, banana]
void clear()import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 2, 3]);
s.clear();
print('after clear: $s, isEmpty ${s.isEmpty}');
s.add(7);
print('still usable: $s');
}after clear: [], isEmpty true still usable: [7]
List<R> cast<R>()import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final Shelf<num> s = Shelf<num>()..addAll([1, 2, 3]);
final List<int> ints = s.cast<int>();
print('cast view: $ints, sum ${ints.reduce((a, b) => a + b)}');
ints[0] = 100;
print('writes go through: $s');
}cast view: [1, 2, 3], sum 6 writes go through: [100, 2, 3]
E removeLast()import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'b', 'c']);
print('removeLast: ${s.removeLast()} -> $s');
print('as a stack: push d, pop ${(s..add('d')).removeLast()}');
}removeLast: c -> [a, b] as a stack: push d, pop d
void sort([int Function(E a, E b)? compare])import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([5, 3, 9, 1]);
s.sort();
print('ascending: $s');
s.sort((a, b) => b.compareTo(a));
print('descending: $s');
final w = Shelf<String>()..addAll(['ccc', 'a', 'bb']);
w.sort((a, b) => a.length - b.length);
print('by length: $w');
}ascending: [1, 3, 5, 9] descending: [9, 5, 3, 1] by length: [a, bb, ccc]
void shuffle([Random? random])import 'raya:collection';
import 'raya:math';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 2, 3, 4, 5, 6]);
s.shuffle(Random(7));
print('shuffled (seed 7): $s');
print('same elements: ${(s.toList()..sort())}');
}shuffled (seed 7): [2, 4, 1, 6, 3, 5] same elements: [1, 2, 3, 4, 5, 6]
Map<int, E> asMap()import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['zero', 'one', 'two']);
final m = s.asMap();
print('asMap: $m');
print('keys: ${m.keys.toList()}, m[2] = ${m[2]}');
}asMap: {0: zero, 1: one, 2: two}
keys: [0, 1, 2], m[2] = twoList<E> sublist(int start, [int? end])import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([0, 1, 2, 3, 4]);
print('sublist(1, 3): ${s.sublist(1, 3)}');
print('sublist(3): ${s.sublist(3)}');
final copy = s.sublist(0, 2)..[0] = 99;
print('a copy: $copy, shelf: $s');
}sublist(1, 3): [1, 2] sublist(3): [3, 4] a copy: [99, 1], shelf: [0, 1, 2, 3, 4]
Iterable<E> getRange(int start, int end)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'b', 'c', 'd']);
print('getRange(1, 3): ${s.getRange(1, 3).toList()}');
print('empty range: ${s.getRange(2, 2).toList()}');
}getRange(1, 3): [b, c] empty range: []
void removeRange(int start, int end)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([0, 1, 2, 3, 4, 5]);
s.removeRange(1, 4);
print('removeRange(1, 4): $s');
}removeRange(1, 4): [0, 4, 5]
void fillRange(int start, int end, [E? fill])import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 2, 3, 4, 5]);
s.fillRange(1, 4, 0);
print('fillRange(1, 4, 0): $s');
}fillRange(1, 4, 0): [1, 0, 0, 0, 5]
void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0])import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'b', 'c', 'd', 'e']);
s.setRange(1, 3, ['X', 'Y']);
print('setRange(1, 3, [X, Y]): $s');
s.setRange(0, 2, ['p', 'q', 'r', 's'], 2);
print('setRange with skipCount 2: $s');
}setRange(1, 3, [X, Y]): [a, X, Y, d, e] setRange with skipCount 2: [r, s, Y, d, e]
void replaceRange(int start, int end, Iterable<E> newContents)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 2, 3, 4]);
s.replaceRange(1, 3, [20, 30, 31]);
print('replace 2 items with 3: $s');
s.replaceRange(0, 2, []);
print('replace 2 with none: $s');
}replace 2 items with 3: [1, 20, 30, 31, 4] replace 2 with none: [30, 31, 4]
int indexOf(Object? element, [int start = 0])import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'b', 'a', 'c']);
print('indexOf a: ${s.indexOf('a')}');
print('indexOf a, 1: ${s.indexOf('a', 1)}');
print('indexOf z: ${s.indexOf('z')}');
}indexOf a: 0 indexOf a, 1: 2 indexOf z: -1
int indexWhere(bool test(E element), [int start = 0])import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([3, 8, 5, 10]);
print('first even at: ${s.indexWhere((x) => x.isEven)}');
print('first even from 2: ${s.indexWhere((x) => x.isEven, 2)}');
print('none: ${s.indexWhere((x) => x > 99)}');
}first even at: 1 first even from 2: 3 none: -1
int lastIndexOf(Object? element, [int? start])import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'b', 'a', 'c']);
print('lastIndexOf a: ${s.lastIndexOf('a')}');
print('lastIndexOf a, 1: ${s.lastIndexOf('a', 1)}');
print('lastIndexOf z: ${s.lastIndexOf('z')}');
}lastIndexOf a: 2 lastIndexOf a, 1: 0 lastIndexOf z: -1
int lastIndexWhere(bool test(E element), [int? start])import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([3, 8, 5, 10, 7]);
print('last even at: ${s.lastIndexWhere((x) => x.isEven)}');
print('last even up to 2: ${s.lastIndexWhere((x) => x.isEven, 2)}');
}last even at: 3 last even up to 2: 1
void insert(int index, E element)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'c']);
s.insert(1, 'b');
s.insert(0, 'start');
s.insert(s.length, 'end');
print('after inserts: $s');
}after inserts: [start, a, b, c, end]
E removeAt(int index)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'b', 'c', 'd']);
print('removeAt(1): ${s.removeAt(1)} -> $s');
print('removeAt(0): ${s.removeAt(0)} -> $s');
}removeAt(1): b -> [a, c, d] removeAt(0): a -> [c, d]
void insertAll(int index, Iterable<E> iterable)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<int>()..addAll([1, 5]);
s.insertAll(1, [2, 3, 4]);
print('insertAll(1, [2, 3, 4]): $s');
}insertAll(1, [2, 3, 4]): [1, 2, 3, 4, 5]
void setAll(int index, Iterable<E> iterable)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<String>()..addAll(['a', 'b', 'c', 'd']);
s.setAll(1, ['X', 'Y']);
print('setAll(1, [X, Y]): $s');
print('length stays ${s.length}');
}setAll(1, [X, Y]): [a, X, Y, d] length stays 4
String toString()import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final s = Shelf<Object?>()..addAll([1, 'two', null]);
print('toString: ${s.toString()}');
print('interpolated: $s');
}toString: [1, two, null] interpolated: [1, two, null]
Operators
List<E> operator +(List<E> other)import 'raya:collection';
// Shelf implements only length, [] and []=; ListBase supplies every other List member.
class Shelf<E> extends ListBase<E> {
final _items = <E?>[];
@override int get length => _items.length;
@override set length(int n) => _items.length = n;
@override E operator [](int i) => _items[i] as E;
@override void operator []=(int i, E v) => _items[i] = v;
}
void main() {
final a = Shelf<int>()..addAll([1, 2]);
final b = a + [3, 4];
print('a + [3, 4] = $b');
print('a unchanged: $a, result is a new List: ${b is! Shelf}');
}a + [3, 4] = [1, 2, 3, 4] a unchanged: [1, 2], result is a new List: true
MapBase
abstract mixin class MapBase<K, V> implements Map<K, V>
Base class for implementing a Map.
This class has a basic implementation of all but five of the members of Map. A basic Map class can be implemented by extending this class and implementing keys, operator[], operator[]=, remove and clear. The remaining operations are implemented in terms of these five.
The keys iterable should have efficient Iterable.length and Iterable.contains operations, and it should catch concurrent modifications of the keys while iterating.
A more efficient implementation is usually possible by overriding some of the other members as well.
Constructors
const MapBase()import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory();
inv['Apples'] = 3;
inv['APPLES'] = 5;
print('inv: $inv');
print("inv['apples']: ${inv['apples']}, is Map: ${inv is Map<String, int>}");
}inv: {apples: 5}
inv['apples']: 5, is Map: trueStatic
static String mapToString(Map<Object?, Object?> m)import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
print('map: ${MapBase.mapToString({'a': 1, 'b': 2})}');
print('empty: ${MapBase.mapToString({})}');
final inv = Inventory()..['Pens'] = 4;
print('Inventory.toString uses it: ${inv.toString() == MapBase.mapToString(inv)}');
}map: {a: 1, b: 2}
empty: {}
Inventory.toString uses it: trueProperties
Iterable<K> get keysIterable<MapEntry<K, V>> get entriesint get lengthbool get isEmptybool get isNotEmptyIterable<V> get valuesMethods
V? remove(Object? key)import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..addAll({'Pens': 4, 'Ink': 2});
print("remove 'PENS': ${inv.remove('PENS')} -> $inv");
print("remove 'clips': ${inv.remove('clips')}");
}remove 'PENS': 4 -> {ink: 2}
remove 'clips': nullvoid clear()import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..addAll({'a': 1, 'b': 2});
inv.clear();
print('after clear: $inv, isEmpty ${inv.isEmpty}');
}after clear: {}, isEmpty trueMap<RK, RV> cast<RK, RV>()import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..addAll({'Pens': 4});
final Map<String, num> view = inv.cast<String, num>();
print('cast view: $view');
print("view['PENS']: ${view['PENS']}");
}cast view: {pens: 4}
view['PENS']: 4void forEach(void action(K key, V value))import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..addAll({'Pens': 4, 'Ink': 2});
var total = 0;
inv.forEach((k, v) {
total += v;
print('$k: $v');
});
print('total items: $total');
}pens: 4 ink: 2 total items: 6
void addAll(Map<K, V> other)import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory();
inv.addAll({'Pens': 1, 'PENS': 9, 'Ink': 2});
print('addAll: $inv (both spellings hit one key)');
}addAll: {pens: 9, ink: 2} (both spellings hit one key)bool containsValue(Object? value)import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..addAll({'Pens': 4, 'Ink': 2});
print('containsValue 2: ${inv.containsValue(2)}');
print('containsValue 7: ${inv.containsValue(7)}');
}containsValue 2: true containsValue 7: false
V putIfAbsent(K key, V ifAbsent())import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..['Pens'] = 4;
print("putIfAbsent 'PENS': ${inv.putIfAbsent('PENS', () => 0)}");
print("putIfAbsent 'Ink': ${inv.putIfAbsent('Ink', () => 10)}");
print('inv: $inv');
}putIfAbsent 'PENS': 4
putIfAbsent 'Ink': 10
inv: {pens: 4, ink: 10}V update(K key, V update(V value), {V Function()? ifAbsent})import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..['Pens'] = 4;
print("update 'PENS' + 1: ${inv.update('PENS', (v) => v + 1)}");
print("update 'Ink' ifAbsent: ${inv.update('Ink', (v) => v + 1, ifAbsent: () => 1)}");
print('inv: $inv');
}update 'PENS' + 1: 5
update 'Ink' ifAbsent: 1
inv: {pens: 5, ink: 1}void updateAll(V update(K key, V value))import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..addAll({'Pens': 4, 'Ink': 2});
inv.updateAll((k, v) => v * 10);
print('after updateAll x10: $inv');
}after updateAll x10: {pens: 40, ink: 20}Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> transform(K key, V value))import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..addAll({'Pens': 4, 'Ink': 2});
final labels = inv.map((k, v) => MapEntry(k.toUpperCase(), '$v units'));
print('map: $labels');
}map: {PENS: 4 units, INK: 2 units}void addEntries(Iterable<MapEntry<K, V>> newEntries)import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory();
inv.addEntries([MapEntry('Pens', 4), MapEntry('ink', 2), MapEntry('INK', 3)]);
print('addEntries: $inv');
}addEntries: {pens: 4, ink: 3}void removeWhere(bool test(K key, V value))import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..addAll({'Pens': 0, 'Ink': 2, 'Clips': 0});
inv.removeWhere((k, v) => v == 0);
print('without empty stock: $inv');
}without empty stock: {ink: 2}bool containsKey(Object? key)import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..['Pens'] = 4;
print("containsKey 'pens': ${inv.containsKey('pens')}");
print("containsKey 'ink': ${inv.containsKey('ink')}");
}containsKey 'pens': true containsKey 'ink': false
String toString()import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..addAll({'Pens': 4, 'Ink': 2});
print('toString: ${inv.toString()}');
}toString: {pens: 4, ink: 2}Operators
V? operator [](Object? key)import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory()..['Pens'] = 4;
print("inv['pens']: ${inv['pens']}");
print("inv['PENS']: ${inv['PENS']}");
print("inv['ink']: ${inv['ink']}");
}inv['pens']: 4 inv['PENS']: 4 inv['ink']: null
operator []=(K key, V value)import 'raya:collection';
// Inventory ignores the case of its keys. It implements [], []=, remove, clear and keys
// (plus containsKey, whose default searches keys); MapBase supplies the rest of Map.
class Inventory extends MapBase<String, int> {
final _m = <String, int>{};
@override int? operator [](Object? k) => k is String ? _m[k.toLowerCase()] : null;
@override void operator []=(String k, int v) => _m[k.toLowerCase()] = v;
@override int? remove(Object? k) => k is String ? _m.remove(k.toLowerCase()) : null;
@override void clear() => _m.clear();
@override Iterable<String> get keys => _m.keys;
@override bool containsKey(Object? k) => k is String && _m.containsKey(k.toLowerCase());
}
void main() {
final inv = Inventory();
inv['Ink'] = 1;
inv['INK'] = 2;
inv['ink'] = 3;
print('three writes, one key: $inv');
}three writes, one key: {ink: 3}UnmodifiableMapBase
abstract class UnmodifiableMapBase<K, V> = MapBase<K, V> with _UnmodifiableMapMixin<K, V>
Basic implementation of an unmodifiable Map.
This class has a basic implementation of all but two of the members of an unmodifiable Map. A simple unmodifiable Map class can be implemented by extending this class and implementing keys and operator[].
Modifying operations throw when used. The remaining non-modifying operations are implemented in terms of keys and operator[].
The keys iterable should have efficient Iterable.length and Iterable.contains operations, and it should catch concurrent modifications of the keys while iterating.
A more efficient implementation is usually possible by overriding some of the other members as well.
MapView
class MapView<K, V> implements Map<K, V>
Wrapper around a class that implements Map that only exposes Map members.
A simple wrapper that delegates all Map members to the map provided in the constructor.
Base for delegating map implementations like UnmodifiableMapView.
Constructors
const MapView(Map<K, V> map)Creates a view which forwards operations to map.
import 'raya:collection';
void main() {
final base = {'a': 1};
final view = MapView(base);
view['b'] = 2;
print('view: $view');
print('base sees the write: $base');
}view: {a: 1, b: 2}
base sees the write: {a: 1, b: 2}Properties
bool get isEmptybool get isNotEmptyint get lengthIterable<K> get keysIterable<V> get valuesIterable<MapEntry<K, V>> get entriesMethods
Map<RK, RV> cast<RK, RV>()import 'raya:collection';
void main() {
final view = MapView<String, num>({'a': 1, 'b': 2});
final Map<String, int> ints = view.cast<String, int>();
print('cast: $ints, a + b = ${ints['a']! + ints['b']!}');
}cast: {a: 1, b: 2}, a + b = 3void addAll(Map<K, V> other)import 'raya:collection';
void main() {
final base = <String, int>{'a': 1};
MapView(base).addAll({'b': 2, 'c': 3});
print('base after view.addAll: $base');
}base after view.addAll: {a: 1, b: 2, c: 3}void clear()import 'raya:collection';
void main() {
final base = {'a': 1, 'b': 2};
MapView(base).clear();
print('base after view.clear: $base');
}base after view.clear: {}V putIfAbsent(K key, V ifAbsent())import 'raya:collection';
void main() {
final base = {'a': 1};
final view = MapView(base);
print("putIfAbsent a: ${view.putIfAbsent('a', () => 9)}");
print("putIfAbsent b: ${view.putIfAbsent('b', () => 2)}");
print('base: $base');
}putIfAbsent a: 1
putIfAbsent b: 2
base: {a: 1, b: 2}bool containsKey(Object? key)import 'raya:collection';
void main() {
final view = MapView({'x': 1});
print("containsKey x: ${view.containsKey('x')}");
print("containsKey y: ${view.containsKey('y')}");
}containsKey x: true containsKey y: false
bool containsValue(Object? value)import 'raya:collection';
void main() {
final view = MapView({'x': 1, 'y': 2});
print('containsValue 2: ${view.containsValue(2)}');
print('containsValue 3: ${view.containsValue(3)}');
}containsValue 2: true containsValue 3: false
void forEach(void action(K key, V value))import 'raya:collection';
void main() {
final view = MapView({'one': 1, 'two': 2});
view.forEach((k, v) => print('$k -> $v'));
}one -> 1 two -> 2
V? remove(Object? key)import 'raya:collection';
void main() {
final base = {'a': 1, 'b': 2};
final view = MapView(base);
print("remove a: ${view.remove('a')}");
print('base: $base');
}remove a: 1
base: {b: 2}String toString()import 'raya:collection';
void main() {
final view = MapView({'a': 1, 'b': 2});
print('toString: ${view.toString()}');
}toString: {a: 1, b: 2}void addEntries(Iterable<MapEntry<K, V>> entries)import 'raya:collection';
void main() {
final base = <String, int>{};
MapView(base).addEntries([MapEntry('a', 1), MapEntry('b', 2)]);
print('base: $base');
}base: {a: 1, b: 2}Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> transform(K key, V value))import 'raya:collection';
void main() {
final view = MapView({'a': 1, 'b': 2});
print('swapped: ${view.map((k, v) => MapEntry(v, k))}');
}swapped: {1: a, 2: b}V update(K key, V update(V value), {V Function()? ifAbsent})import 'raya:collection';
void main() {
final base = {'hits': 1};
final view = MapView(base);
view.update('hits', (v) => v + 1);
view.update('misses', (v) => v + 1, ifAbsent: () => 1);
print('base: $base');
}base: {hits: 2, misses: 1}void updateAll(V update(K key, V value))import 'raya:collection';
void main() {
final base = {'a': 1, 'b': 2};
MapView(base).updateAll((k, v) => v * 100);
print('base: $base');
}base: {a: 100, b: 200}void removeWhere(bool test(K key, V value))import 'raya:collection';
void main() {
final base = {'a': 1, 'b': 2, 'c': 3};
MapView(base).removeWhere((k, v) => v.isOdd);
print('base: $base');
}base: {b: 2}Operators
V? operator [](Object? key)import 'raya:collection';
void main() {
final view = MapView({'a': 1});
print("view['a']: ${view['a']}");
print("view['z']: ${view['z']}");
}view['a']: 1 view['z']: null
void operator []=(K key, V value)import 'raya:collection';
void main() {
final base = <String, int>{};
final view = MapView(base);
view['a'] = 1;
print('base after view[a] = 1: $base');
}base after view[a] = 1: {a: 1}UnmodifiableMapView
class UnmodifiableMapView<K, V> extends MapView<K, V> with _UnmodifiableMapMixin<K, V>
View of a Map that disallow modifying the map.
A wrapper around a Map that forwards all members to the map provided in the constructor, except for operations that modify the map. Modifying operations throw instead.
final baseMap = <int, String>{1: 'Mars', 2: 'Mercury', 3: 'Venus'};
final unmodifiableMapView = UnmodifiableMapView(baseMap);
// Remove an entry from the original map.
baseMap.remove(3);
print(unmodifiableMapView); // {1: Mars, 2: Mercury}
unmodifiableMapView.remove(1); // Throws.import 'raya:collection';
void main() {
final view = UnmodifiableMapView({'a': 1});
print(view['a']);
try {
view['b'] = 2;
} on UnsupportedError {
print('the map view is read-only');
}
}1 the map view is read-only
Constructors
UnmodifiableMapView(Map<K, V> map)import 'raya:collection';
void main() {
final config = {'debug': false, 'retries': 3};
final view = UnmodifiableMapView(config);
print('view: $view');
try {
view['debug'] = true;
} on UnsupportedError {
print('view[...] = ... -> UnsupportedError');
}
}view: {debug: false, retries: 3}
view[...] = ... -> UnsupportedErrorMethods
Map<RK, RV> cast<RK, RV>()import 'raya:collection';
void main() {
final view = UnmodifiableMapView<String, Object>({'a': 1, 'b': 2});
final ints = view.cast<String, int>();
print('cast: a+b = ${ints['a']! + ints['b']!}');
}cast: a+b = 3
Queue
abstract interface class Queue<E> implements Iterable<E>, _QueueIterable<E>
A Queue is a collection that can be manipulated at both ends. One can iterate over the elements of a queue through forEach or with an Iterator.
It is generally not allowed to modify the queue (add or remove entries) while an operation in the queue is being performed, for example during a call to forEach. Modifying the queue while it is being iterated will most likely break the iteration. This goes both for using the iterator directly, or for iterating an Iterable returned by a method like map or where.
Example:
final queue = Queue<int>(); // ListQueue() by default
print(queue.runtimeType); // ListQueue
// Adding items to queue
queue.addAll([1, 2, 3]);
queue.addFirst(0);
queue.addLast(10);
print(queue); // {0, 1, 2, 3, 10}
// Removing items from queue
queue.removeFirst();
queue.removeLast();
print(queue); // {1, 2, 3}import 'raya:collection';
void main() {
final q = Queue<String>()..addAll(['a', 'b']);
q.addFirst('start');
q.addLast('end');
print('queue: $q');
print('removeFirst: ${q.removeFirst()}');
print('removeLast: ${q.removeLast()}');
print('left: $q, length ${q.length}');
}queue: {start, a, b, end}
removeFirst: start
removeLast: end
left: {a, b}, length 2Constructors
factory Queue() = ListQueue<E>Creates a queue.
import 'raya:collection';
void main() {
final q = Queue<String>();
q.add('first');
q.add('second');
q.addFirst('urgent');
print('queue: $q');
print('removeFirst: ${q.removeFirst()}, now $q');
print('default implementation: ${q is ListQueue}');
}queue: {urgent, first, second}
removeFirst: urgent, now {first, second}
default implementation: truefactory Queue.from(Iterable elements) = ListQueue<E>.fromCreates a queue containing all elements.
The element order in the queue is as if the elements were added using addLast in the order provided by elements.iterator.
All the elements should be instances of E. The elements iterable itself may have any element type, so this constructor can be used to down-cast a Queue, for example as:
Queue<SuperType> superQueue = ...;
Queue<SubType> subQueue =
Queue<SubType>.from(superQueue.whereType<SubType>());import 'raya:collection';
void main() {
final List<dynamic> raw = [1, 2, 3];
final q = Queue<int>.from(raw);
print('queue from list: $q, first ${q.first}, last ${q.last}');
}queue from list: {1, 2, 3}, first 1, last 3factory Queue.of(Iterable<E> elements) = ListQueue<E>.ofCreates a queue from elements.
The element order in the queue is as if the elements were added using addLast in the order provided by elements.iterator.
import 'raya:collection';
void main() {
final q = Queue.of(['a', 'b', 'c']);
q.addLast('d');
print('queue: $q');
print('take two from the front: ${q.removeFirst()}, ${q.removeFirst()} -> $q');
}queue: {a, b, c, d}
take two from the front: a, b -> {c, d}Static
static Queue<T> castFrom<S, T>(Queue<S> source)Adapts source to be a Queue<T>.
Any time the queue would produce an element that is not a T, the element access will throw.
When a T value is stored into the adapted queue, the operation will throw unless the value is also an instance of S.
If all accessed elements of source are actually instances of T, and if all elements stored into the returned queue are actually instances of S, then the returned queue can be used as a Queue<T>.
Methods which accept Object? as argument, like contains and remove, will pass the argument directly to this queue's method without any checks.
import 'raya:collection';
void main() {
final Queue<Object> objects = Queue.of(<Object>[1, 2, 3]);
final ints = Queue.castFrom<Object, int>(objects);
print('castFrom view: $ints, sum ${ints.fold(0, (a, b) => a + b)}');
ints.addLast(4);
print('writes go through to the source: $objects');
}castFrom view: {1, 2, 3}, sum 6
writes go through to the source: {1, 2, 3, 4}Methods
Queue<R> cast<R>()Provides a view of this queue as a queue of R instances, if necessary.
If this queue contains only instances of R, all read operations will work correctly. If any operation tries to access an element that is not an instance of R, the access will throw instead.
Elements added to the queue (e.g. by using addFirst or addAll) must be instances of R to be valid arguments to the adding function, and they must also be instances of E to be accepted by this queue as well.
Methods which accept Object? as argument, like contains and remove, will pass the argument directly to the this queue's method without any checks. That means that you can do queueOfStrings.cast<int>.remove("a") successfully, even if it looks like it shouldn't have any effect.
import 'raya:collection';
void main() {
final Queue<num> nums = Queue.of(<num>[1, 2, 3]);
final ints = nums.cast<int>();
print('cast<int>: $ints, first.isEven ${ints.first.isEven}');
}cast<int>: {1, 2, 3}, first.isEven falseE removeFirst()Removes and returns the first element of this queue.
The queue must not be empty when this method is called.
import 'raya:collection';
// Breadth-first search over a small graph, with a Queue as the frontier.
void main() {
const graph = {
'a': ['b', 'c'], 'b': ['d'], 'c': ['d', 'e'], 'd': ['f'], 'e': ['f'], 'f': <String>[],
};
final dist = {'a': 0};
final q = Queue.of(['a']);
while (q.isNotEmpty) {
final v = q.removeFirst();
for (final w in graph[v]!) {
if (!dist.containsKey(w)) {
dist[w] = dist[v]! + 1;
q.addLast(w);
}
}
}
print('steps from a: $dist');
}steps from a: {a: 0, b: 1, c: 1, d: 2, e: 2, f: 3}E removeLast()Removes and returns the last element of the queue.
The queue must not be empty when this method is called.
import 'raya:collection';
void main() {
final q = Queue.of([1, 2, 3]);
print('removeLast: ${q.removeLast()}, queue $q');
q.clear();
try {
q.removeLast();
} on StateError catch (e) {
print('empty queue -> StateError: ${e.message}');
}
}removeLast: 3, queue {1, 2}
empty queue -> StateError: No elementvoid addFirst(E value)Adds value at the beginning of the queue.
import 'raya:collection';
void main() {
// Use a Queue as a stack by pushing and popping at the front.
final stack = Queue<int>();
for (final x in [1, 2, 3]) {
stack.addFirst(x);
}
print('stack: $stack, pop: ${stack.removeFirst()}');
}stack: {3, 2, 1}, pop: 3void addLast(E value)Adds value at the end of the queue.
import 'raya:collection';
void main() {
final q = Queue<String>();
q.addLast('ann');
q.addLast('bob');
q.addLast('cy');
print('served in arrival order:');
while (q.isNotEmpty) {
print(' ${q.removeFirst()}');
}
}served in arrival order: ann bob cy
void add(E value)Adds value at the end of the queue.
import 'raya:collection';
void main() {
final q = Queue<int>()..add(1)..add(2);
q.add(3);
print('add puts at the end: $q');
}add puts at the end: {1, 2, 3}bool remove(Object? value)Removes a single instance of value from the queue.
Returns true if a value was removed, or false if the queue contained no element equal to value.
import 'raya:collection';
void main() {
final q = Queue.of(['a', 'b', 'a']);
print('remove("a"): ${q.remove('a')} -> $q (first match only)');
print('remove("z"): ${q.remove('z')}');
}remove("a"): true -> {b, a} (first match only)
remove("z"): falsevoid addAll(Iterable<E> iterable)Adds all elements of iterable at the end of the queue. The length of the queue is extended by the length of iterable.
import 'raya:collection';
void main() {
final q = Queue.of([1]);
q.addAll([2, 3, 4]);
print('after addAll: $q, length ${q.length}');
}after addAll: {1, 2, 3, 4}, length 4void removeWhere(bool test(E element))Removes all elements matched by test from the queue.
The test function must not throw or modify the queue.
import 'raya:collection';
void main() {
final q = Queue.of(List.generate(10, (i) => i));
q.removeWhere((x) => x.isOdd);
print('evens left: $q');
}evens left: {0, 2, 4, 6, 8}void retainWhere(bool test(E element))Removes all elements not matched by test from the queue.
The test function must not throw or modify the queue.
import 'raya:collection';
void main() {
final q = Queue.of(['apple', 'kiwi', 'banana', 'fig']);
q.retainWhere((w) => w.length > 3);
print('long words kept: $q');
}long words kept: {apple, kiwi, banana}void clear()Removes all elements in the queue. The size of the queue becomes zero.
import 'raya:collection';
void main() {
final q = Queue.of([1, 2, 3]);
q.clear();
print('after clear: $q, isEmpty ${q.isEmpty}');
}after clear: {}, isEmpty trueDoubleLinkedQueue
final class DoubleLinkedQueue<E> extends Iterable<E> implements Queue<E>
A Queue implementation based on a double-linked list.
Allows constant time add, remove-at-ends and peek operations.
import 'raya:collection';
void main() {
final q = DoubleLinkedQueue<int>.from([1, 2, 3]);
q.addFirst(0);
print(q);
print('first entry: ${q.firstEntry()!.element}');
}{0, 1, 2, 3}
first entry: 0Constructors
DoubleLinkedQueue()import 'raya:collection';
void main() {
final q = DoubleLinkedQueue<int>();
q..add(2)..addFirst(1)..addLast(3);
print('queue: $q');
print('removeFirst ${q.removeFirst()}, removeLast ${q.removeLast()}, left $q');
}queue: {1, 2, 3}
removeFirst 1, removeLast 3, left {2}factory DoubleLinkedQueue.from(Iterable<dynamic> elements)Creates a double-linked queue containing all elements.
The element order in the queue is as if the elements were added using addLast in the order provided by elements.iterator.
All the elements should be instances of E. The elements iterable itself may have any element type, so this constructor can be used to down-cast a Queue, for example as:
Queue<SuperType> superQueue = ...;
Queue<SubType> subQueue =
DoubleLinkedQueue<SubType>.from(superQueue.whereType<SubType>());import 'raya:collection';
void main() {
final List<Object> raw = ['x', 'y'];
final q = DoubleLinkedQueue<String>.from(raw);
print('from: $q');
}from: {x, y}factory DoubleLinkedQueue.of(Iterable<E> elements)Creates a double-linked queue from elements.
The element order in the queue is as if the elements were added using addLast in the order provided by elements.iterator.
import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of([10, 20, 30]);
print('of: $q, first ${q.first}, last ${q.last}');
}of: {10, 20, 30}, first 10, last 30Properties
int get lengthE get firstE get lastE get singlebool get isEmpty_DoubleLinkedQueueIterator<E> get iteratorMethods
Queue<R> cast<R>()import 'raya:collection';
void main() {
final DoubleLinkedQueue<num> nums = DoubleLinkedQueue.of(<num>[1, 2]);
final ints = nums.cast<int>();
print('cast<int>: $ints, ${ints.first.bitLength} bit(s) in the first');
}cast<int>: {1, 2}, 1 bit(s) in the firstvoid addLast(E value)import 'raya:collection';
void main() {
final q = DoubleLinkedQueue<String>()..addLast('a')..addLast('b');
print('addLast twice: $q');
}addLast twice: {a, b}void addFirst(E value)import 'raya:collection';
void main() {
final q = DoubleLinkedQueue<String>()..addFirst('b')..addFirst('a');
print('addFirst twice: $q');
}addFirst twice: {a, b}void add(E value)import 'raya:collection';
void main() {
final q = DoubleLinkedQueue<int>();
q.add(1);
q.add(2);
print('add appends: $q');
}add appends: {1, 2}void addAll(Iterable<E> iterable)import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of([0]);
q.addAll([1, 2, 3]);
print('after addAll: $q');
}after addAll: {0, 1, 2, 3}E removeLast()import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of(['a', 'b', 'c']);
print('removeLast: ${q.removeLast()} -> $q');
}removeLast: c -> {a, b}E removeFirst()import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of(['a', 'b', 'c']);
print('removeFirst: ${q.removeFirst()} -> $q');
q.clear();
try {
q.removeFirst();
} on StateError {
print('empty -> StateError');
}
}removeFirst: a -> {b, c}
empty -> StateErrorbool remove(Object? o)import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of([1, 2, 1, 3]);
print('remove(1): ${q.remove(1)} -> $q');
print('remove(9): ${q.remove(9)}');
}remove(1): true -> {2, 1, 3}
remove(9): falsevoid removeWhere(bool test(E element))import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of(['ok', 'error: x', 'ok', 'error: y']);
q.removeWhere((s) => s.startsWith('error'));
print('without errors: $q');
}without errors: {ok, ok}void retainWhere(bool test(E element))import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of([5, 12, 7, 20]);
q.retainWhere((x) => x >= 10);
print('kept >= 10: $q');
}kept >= 10: {12, 20}DoubleLinkedQueueEntry<E>? firstEntry()The entry object of the first element in the queue.
Each element of the queue has an associated DoubleLinkedQueueEntry.
Returns the entry object corresponding to the first element of the queue, or null if the queue is empty.
The entry objects can also be accessed using lastEntry, and they can be iterated using DoubleLinkedQueueEntry.nextEntry and DoubleLinkedQueueEntry.previousEntry.
import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of(['a', 'b', 'c']);
final e = q.firstEntry()!;
print('firstEntry: ${e.element}, next: ${e.nextEntry()?.element}');
print('empty queue firstEntry: ${DoubleLinkedQueue<int>().firstEntry()}');
}firstEntry: a, next: b empty queue firstEntry: null
DoubleLinkedQueueEntry<E>? lastEntry()The entry object of the last element in the queue.
Each element of the queue has an associated DoubleLinkedQueueEntry.
Returns the entry object corresponding to the last element of the queue, or null if the queue is empty.
The entry objects can also be accessed using firstEntry, and they can be iterated using DoubleLinkedQueueEntry.nextEntry and DoubleLinkedQueueEntry.previousEntry.
import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of([1, 2, 3]);
final e = q.lastEntry()!;
e.element = 30; // entries are mutable handles into the queue
print('lastEntry was 3, set to 30: $q');
}lastEntry was 3, set to 30: {1, 2, 30}void clear()import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of([1, 2, 3])..clear();
print('after clear: $q, length ${q.length}');
}after clear: {}, length 0void forEachEntry(void action(DoubleLinkedQueueEntry<E> element))Calls action for each entry object of this double-linked queue.
Each element of the queue has an associated DoubleLinkedQueueEntry. This method iterates the entry objects from first to last and calls action with each object in turn.
The entry objects can also be accessed using firstEntry and lastEntry, and iterated using DoubleLinkedQueueEntry.nextEntry and DoubleLinkedQueueEntry.previousEntry.
The action function can use methods on DoubleLinkedQueueEntry to remove the entry or it can insert elements before or after the entry. If the current entry is removed, iteration continues with the entry that was following the current entry when action was called. Any elements inserted after the current element before it is removed will not be visited by the iteration.
import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of([1, 2, 3, 4, 5]);
// Entries allow removal and insertion while walking.
q.forEachEntry((e) {
if (e.element.isEven) e.remove();
if (e.element == 5) e.append(6);
});
print('evens removed, 6 appended after 5: $q');
}evens removed, 6 appended after 5: {1, 3, 5}String toString()import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of(['x', 'y']);
print('toString: ${q.toString()}');
print('empty: ${DoubleLinkedQueue<int>()}');
}toString: {x, y}
empty: {}ListQueue
final class ListQueue<E> extends ListIterable<E> implements Queue<E>
List based Queue.
Keeps a cyclic buffer of elements, and grows to a larger buffer when it fills up. This guarantees constant time peek and remove operations, and amortized constant time add operations.
The structure is efficient for any queue or stack usage.
Example:
final queue = ListQueue<int>();
To add objects to a queue, use add, addAll, addFirst oraddLast.
queue.add(5);
queue.addFirst(0);
queue.addLast(10);
queue.addAll([1, 2, 3]);
print(queue); // {0, 5, 10, 1, 2, 3}
To check if the queue is empty, use isEmpty or isNotEmpty. To find the number of queue entries, use length.
final isEmpty = queue.isEmpty; // false
final queueSize = queue.length; // 6
To get first or last item from queue, use first or last.
final first = queue.first; // 0
final last = queue.last; // 3
To get item value using index, use elementAt.
final itemAt = queue.elementAt(2); // 10
To convert queue to list, call toList.
final numbers = queue.toList();
print(numbers); // [0, 5, 10, 1, 2, 3]
To remove item from queue, call remove, removeFirst or removeLast.
queue.remove(10);
queue.removeFirst();
queue.removeLast();
print(queue); // {5, 1, 2}
To remove multiple elements at the same time, use removeWhere.
queue.removeWhere((element) => element == 1);
print(queue); // {5, 2}
To remove all elements in this queue that do not meet a condition, use retainWhere.
queue.retainWhere((element) => element < 4);
print(queue); // {2}
To remove all items and empty the set, use clear.
queue.clear();
print(queue.isEmpty); // true
print(queue); // {}import 'raya:collection';
void main() {
// A sliding window of the last 3 values.
final window = ListQueue<int>();
for (final x in [4, 8, 15, 16, 23, 42]) {
window.addLast(x);
if (window.length > 3) window.removeFirst();
final avg = window.reduce((a, b) => a + b) / window.length;
print('after $x: window $window, average ${avg.toStringAsFixed(2)}');
}
}after 4: window {4}, average 4.00
after 8: window {4, 8}, average 6.00
after 15: window {4, 8, 15}, average 9.00
after 16: window {8, 15, 16}, average 13.00
after 23: window {15, 16, 23}, average 18.00
after 42: window {16, 23, 42}, average 27.00Constructors
ListQueue([int? initialCapacity])Create an empty queue.
If initialCapacity is given, prepare the queue for at least that many elements.
import 'raya:collection';
void main() {
final q = ListQueue<int>(16); // capacity hint; grows as needed
for (var i = 1; i <= 5; i++) {
q.addLast(i);
}
print('queue: $q, length ${q.length}');
print('elementAt(2): ${q.elementAt(2)} (constant time, backed by a ring buffer)');
}queue: {1, 2, 3, 4, 5}, length 5
elementAt(2): 3 (constant time, backed by a ring buffer)factory ListQueue.from(Iterable<dynamic> elements)Create a ListQueue containing all elements.
The elements are added to the queue, as by addLast, in the order given by elements.iterator.
All the elements should be instances of E. The elements iterable itself may have any element type, so this constructor can be used to down-cast a Queue, for example as:
Queue<SuperType> superQueue = ...;
Queue<SubType> subQueue =
ListQueue<SubType>.from(superQueue.whereType<SubType>());
Example:
final numbers = <num>[10, 20, 30];
final queue = ListQueue<int>.from(numbers);
print(queue); // {10, 20, 30}import 'raya:collection';
void main() {
final Iterable<dynamic> raw = [3, 2, 1];
final q = ListQueue<int>.from(raw);
print('from: $q');
}from: {3, 2, 1}factory ListQueue.of(Iterable<E> elements)Create a ListQueue from elements.
The elements are added to the queue, as by addLast, in the order given by elements.iterator. Example:
final baseQueue = ListQueue.of([1.0, 2.0, 3.0]); // A ListQueue<double>
final numQueue = ListQueue<num>.of(baseQueue);
print(numQueue); // {1.0, 2.0, 3.0}import 'raya:collection';
void main() {
final q = ListQueue.of('abc'.split(''));
q.addFirst('_');
print('of + addFirst: $q');
}of + addFirst: {_, a, b, c}Properties
Iterator<E> get iteratorbool get isEmptyint get lengthE get firstE get lastE get singleMethods
Queue<R> cast<R>()import 'raya:collection';
void main() {
final ListQueue<Object> objs = ListQueue.of(<Object>['a', 'b']);
final strs = objs.cast<String>();
print('cast<String>: ${strs.map((s) => s.toUpperCase()).toList()}');
}cast<String>: [A, B]
void forEach(void f(E element))import 'raya:collection';
void main() {
final q = ListQueue.of([2, 4, 6]);
var total = 0;
q.forEach((x) => total += x);
print('sum via forEach: $total');
}sum via forEach: 12
E elementAt(int index)import 'raya:collection';
void main() {
final q = ListQueue.of(['a', 'b', 'c']);
q.removeFirst();
q.addLast('d');
print('elementAt(0) = ${q.elementAt(0)}, elementAt(2) = ${q.elementAt(2)}');
try {
q.elementAt(3);
} on RangeError {
print('elementAt(3) -> RangeError');
}
}elementAt(0) = b, elementAt(2) = d elementAt(3) -> RangeError
List<E> toList({bool growable = true})import 'raya:collection';
void main() {
final q = ListQueue.of([1, 2, 3]);
final fixed = q.toList(growable: false);
print('toList: $fixed');
try {
fixed.add(4);
} on UnsupportedError {
print('growable: false -> add throws UnsupportedError');
}
}toList: [1, 2, 3] growable: false -> add throws UnsupportedError
void add(E value)import 'raya:collection';
void main() {
final q = ListQueue<String>()..add('a')..add('b');
print('add appends: $q');
}add appends: {a, b}void addAll(Iterable<E> elements)import 'raya:collection';
void main() {
final q = ListQueue<int>()..addAll([1, 2])..addAll({3, 4});
print('addAll from list and set: $q');
}addAll from list and set: {1, 2, 3, 4}bool remove(Object? value)import 'raya:collection';
void main() {
final q = ListQueue.of(['x', 'y', 'x']);
print('remove("x"): ${q.remove('x')} -> $q');
}remove("x"): true -> {y, x}void removeWhere(bool test(E element))Remove all elements matched by test.
This method is inefficient since it works by repeatedly removing single elements, each of which can take linear time.
import 'raya:collection';
void main() {
final q = ListQueue.of([1, 2, 3, 4, 5, 6]);
q.removeWhere((x) => x % 3 == 0);
print('multiples of 3 removed: $q');
}multiples of 3 removed: {1, 2, 4, 5}void retainWhere(bool test(E element))Remove all elements not matched by test.
This method is inefficient since it works by repeatedly removing single elements, each of which can take linear time.
import 'raya:collection';
void main() {
final q = ListQueue.of(['a1', 'b2', 'a3']);
q.retainWhere((s) => s.startsWith('a'));
print('kept a*: $q');
}kept a*: {a1, a3}void clear()import 'raya:collection';
void main() {
final q = ListQueue.of([1, 2, 3])..clear();
print('after clear: $q, isEmpty ${q.isEmpty}');
}after clear: {}, isEmpty trueString toString()import 'raya:collection';
void main() {
final q = ListQueue.of([1, 2, 3]);
print('toString: ${q.toString()}');
print('uses braces like other Iterables: ${q.toString().startsWith('{')}');
}toString: {1, 2, 3}
uses braces like other Iterables: truevoid addLast(E value)import 'raya:collection';
void main() {
// Sliding window of the last 3 readings.
final window = ListQueue<int>();
for (final r in [5, 8, 2, 9, 4]) {
window.addLast(r);
if (window.length > 3) window.removeFirst();
print('after $r: $window');
}
}after 5: {5}
after 8: {5, 8}
after 2: {5, 8, 2}
after 9: {8, 2, 9}
after 4: {2, 9, 4}void addFirst(E value)import 'raya:collection';
void main() {
final q = ListQueue.of([2, 3]);
q.addFirst(1);
q.addFirst(0);
print('addFirst 1 then 0: $q');
}addFirst 1 then 0: {0, 1, 2, 3}E removeFirst()import 'raya:collection';
void main() {
// Breadth-first walk of a small tree.
final tree = {1: [2, 3], 2: [4], 3: [5, 6]};
final q = ListQueue.of([1]);
final order = <int>[];
while (q.isNotEmpty) {
final n = q.removeFirst();
order.add(n);
q.addAll(tree[n] ?? const []);
}
print('BFS order: $order');
}BFS order: [1, 2, 3, 4, 5, 6]
E removeLast()import 'raya:collection';
void main() {
final q = ListQueue.of([1, 2, 3]);
print('removeLast: ${q.removeLast()} -> $q');
}removeLast: 3 -> {1, 2}SetBase
abstract mixin class SetBase<E> implements Set<E>
Base implementation of Set.
This class provides a base implementation of a Set that depends only on the abstract members: add, contains, lookup, remove, iterator, length and toSet.
Some of the methods assume that toSet creates a modifiable set. If using this base class for an unmodifiable set, where toSet should return an unmodifiable set, it's necessary to reimplement retainAll, union, intersection and difference.
Implementations of Set using this base should consider also implementing clear in constant time. The default implementation works by removing every element.
Constructors
const SetBase()import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['Red', 'red', 'Blue']);
print('tags: $t, length ${t.length}');
print('contains RED: ${t.contains('RED')}');
print('is Set: ${t is Set<String>}');
}tags: {Red, Blue}, length 2
contains RED: true
is Set: trueStatic
static String setToString(Set set)Converts set to a string by converting each element to a string (by calling Object.toString), joining them with ", ", and wrapping the result in "{" and "}".
Handles circular references where converting one of the elements to a string ends up converting set to a string again.
import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
print('ints: ${SetBase.setToString({1, 2, 3})}');
print('empty: ${SetBase.setToString(<int>{})}');
final t = Tags()..addAll(['A', 'b']);
print('Tags.toString uses it: ${t.toString() == SetBase.setToString(t)}');
}ints: {1, 2, 3}
empty: {}
Tags.toString uses it: trueProperties
Iterator<E> get iteratorint get lengthbool get isEmptybool get isNotEmptyE get singleE get firstE get lastMethods
bool add(E value)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags();
print("add 'Raya': ${t.add('Raya')}");
print("add 'RAYA': ${t.add('RAYA')}");
print('tags: $t (the first spelling is kept)');
}add 'Raya': true
add 'RAYA': false
tags: {Raya} (the first spelling is kept)bool contains(Object? element)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['Maths', 'Physics']);
print("contains 'maths': ${t.contains('maths')}");
print("contains 'biology': ${t.contains('biology')}");
print('contains 42: ${t.contains(42)}');
}contains 'maths': true contains 'biology': false contains 42: false
E? lookup(Object? element)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['NewYork', 'Paris']);
print("lookup 'newyork': ${t.lookup('newyork')}");
print("lookup 'rome': ${t.lookup('rome')}");
}lookup 'newyork': NewYork lookup 'rome': null
bool remove(Object? value)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['Alpha', 'Beta']);
print("remove 'ALPHA': ${t.remove('ALPHA')} -> $t");
print("remove 'gamma': ${t.remove('gamma')} -> $t");
}remove 'ALPHA': true -> {Beta}
remove 'gamma': false -> {Beta}Set<E> toSet()import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['One', 'Two']);
final copy = t.toSet();
copy.add('three');
print('copy: $copy');
print('original: $t');
print('copy still ignores case: ${copy.contains('ONE')}');
}copy: {One, Two, three}
original: {One, Two}
copy still ignores case: trueSet<R> cast<R>()import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['x', 'y']);
final Set<Object> objs = t.cast<Object>();
print('cast view: $objs, length ${objs.length}');
print("contains 'X': ${objs.contains('X')}");
}cast view: {x, y}, length 2
contains 'X': trueIterable<E> followedBy(Iterable<E> other)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['a', 'b']);
print('followedBy: ${t.followedBy(['A', 'c']).toList()}');
print('(a plain iterable, so A repeats)');
}followedBy: [a, b, A, c] (a plain iterable, so A repeats)
Iterable<T> whereType<T>()import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['a', 'b']);
print('whereType<String>: ${t.whereType<String>().toList()}');
print('whereType<int>: ${t.whereType<int>().toList()}');
}whereType<String>: [a, b] whereType<int>: []
void clear()import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['a', 'b', 'c']);
t.clear();
print('after clear: $t, isEmpty ${t.isEmpty}');
}after clear: {}, isEmpty truevoid addAll(Iterable<E> elements)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags();
t.addAll(['Cat', 'cat', 'CAT', 'Dog']);
print('addAll of 4 spellings: $t');
}addAll of 4 spellings: {Cat, Dog}void removeAll(Iterable<Object?> elements)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['a', 'b', 'c', 'd']);
t.removeAll(['A', 'C', 'z']);
print('removeAll [A, C, z]: $t');
}removeAll [A, C, z]: {b, d}void retainAll(Iterable<Object?> elements)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['Red', 'Green', 'Blue']);
t.retainAll(['RED', 'blue', 'black']);
print('retainAll: $t');
}retainAll: {Red, Blue}void removeWhere(bool test(E element))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['ant', 'bear', 'cat', 'deer']);
t.removeWhere((w) => w.length == 3);
print('without 3-letter words: $t');
}without 3-letter words: {bear, deer}void retainWhere(bool test(E element))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['apple', 'Avocado', 'banana']);
t.retainWhere((w) => w.toLowerCase().startsWith('a'));
print('starting with a: $t');
}starting with a: {apple, Avocado}bool containsAll(Iterable<Object?> other)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['x', 'y', 'z']);
print('containsAll [X, Y]: ${t.containsAll(['X', 'Y'])}');
print('containsAll [x, w]: ${t.containsAll(['x', 'w'])}');
}containsAll [X, Y]: true containsAll [x, w]: false
Set<E> union(Set<E> other)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final a = Tags()..addAll(['Red', 'Blue']);
final b = Tags()..addAll(['blue', 'Green']);
print('union: ${a.union(b)}');
}union: {Red, Blue, Green}Set<E> intersection(Set<Object?> other)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final a = Tags()..addAll(['Red', 'Blue', 'Green']);
print("intersection with {'BLUE', 'green', 'pink'}: ${a.intersection({'BLUE', 'green', 'pink'})}");
}intersection with {'BLUE', 'green', 'pink'}: {}Set<E> difference(Set<Object?> other)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final a = Tags()..addAll(['Red', 'Blue', 'Green']);
print("difference with {'BLUE'}: ${a.difference({'BLUE'})}");
}difference with {'BLUE'}: {Red, Blue, Green}List<E> toList({bool growable = true})import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['b', 'a', 'B']);
final l = t.toList();
print('toList: $l, length ${l.length}');
print('sorted copy: ${l..sort()}');
}toList: [b, a], length 2 sorted copy: [a, b]
Iterable<T> map<T>(T f(E element))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['one', 'three']);
print('lengths: ${t.map((w) => w.length).toList()}');
print('upper: ${t.map((w) => w.toUpperCase()).toSet()}');
}lengths: [3, 5]
upper: {ONE, THREE}String toString()import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['x', 'Y']);
print('toString: ${t.toString()}');
print('interpolated: $t');
}toString: {x, Y}
interpolated: {x, Y}Iterable<E> where(bool f(E element))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['sun', 'moon', 'star', 'sky']);
print("starting with s: ${t.where((w) => w.startsWith('s')).toList()}");
}starting with s: [sun, star, sky]
Iterable<T> expand<T>(Iterable<T> f(E element))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['ab', 'cd']);
print('letters: ${t.expand((w) => w.split('')).toList()}');
}letters: [a, b, c, d]
void forEach(void f(E element))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['Raya', 'raya', 'Evelyn']);
t.forEach((w) => print('tag: $w'));
}tag: Raya tag: Evelyn
E reduce(E combine(E value, E element))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['kiwi', 'banana', 'fig']);
print('longest: ${t.reduce((a, b) => b.length > a.length ? b : a)}');
}longest: banana
T fold<T>(T initialValue, T combine(T previousValue, E element))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['a', 'bb', 'A', 'ccc']);
print('total letters: ${t.fold<int>(0, (n, w) => n + w.length)}');
}total letters: 6
bool every(bool f(E element))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['Ant', 'Arc']);
print("every starts with A: ${t.every((w) => w.startsWith('A'))}");
t.add('bee');
print("after adding bee: ${t.every((w) => w.startsWith('A'))}");
}every starts with A: true after adding bee: false
String join([String separator = ""])import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['x', 'y', 'X', 'z']);
print("join(', '): ${t.join(', ')}");
print('join(): ${t.join()}');
}join(', '): x, y, z
join(): xyzbool any(bool test(E element))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['one', 'two']);
print('any longer than 2: ${t.any((w) => w.length > 2)}');
print('any empty: ${t.any((w) => w.isEmpty)}');
}any longer than 2: true any empty: false
Iterable<E> take(int n)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['a', 'b', 'c', 'd']);
print('take(2): ${t.take(2).toList()}');
}take(2): [a, b]
Iterable<E> takeWhile(bool test(E value))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['aa', 'bb', 'c', 'dd']);
print('takeWhile(length 2): ${t.takeWhile((w) => w.length == 2).toList()}');
}takeWhile(length 2): [aa, bb]
Iterable<E> skip(int n)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['a', 'b', 'c', 'd']);
print('skip(3): ${t.skip(3).toList()}');
}skip(3): [d]
Iterable<E> skipWhile(bool test(E value))import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['aa', 'bb', 'c', 'dd']);
print('skipWhile(length 2): ${t.skipWhile((w) => w.length == 2).toList()}');
}skipWhile(length 2): [c, dd]
E firstWhere(bool test(E value), {E Function()? orElse})import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['pear', 'Plum', 'apple']);
print("first with l: ${t.firstWhere((w) => w.contains('l'))}");
print("orElse: ${t.firstWhere((w) => w.contains('z'), orElse: () => 'none')}");
}first with l: Plum orElse: none
E lastWhere(bool test(E value), {E Function()? orElse})import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['pear', 'Plum', 'apple']);
print("last with p: ${t.lastWhere((w) => w.toLowerCase().contains('p'))}");
}last with p: apple
E singleWhere(bool test(E value), {E Function()? orElse})import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['red', 'green', 'blue']);
print("only one with u: ${t.singleWhere((w) => w.contains('u'))}");
try {
t.singleWhere((w) => w.contains('e'));
} on StateError catch (e) {
print('several with e: ${e.message}');
}
}only one with u: blue several with e: Too many elements
E elementAt(int index)import 'raya:collection';
// Tags ignores case. It implements seven members; SetBase supplies the rest of Set.
class Tags extends SetBase<String> {
final _m = <String, String>{};
@override bool add(String v) => !contains(v) && (_m[v.toLowerCase()] = v) == v;
@override bool contains(Object? e) => e is String && _m.containsKey(e.toLowerCase());
@override String? lookup(Object? e) => e is String ? _m[e.toLowerCase()] : null;
@override bool remove(Object? v) => v is String && _m.remove(v.toLowerCase()) != null;
@override Iterator<String> get iterator => _m.values.iterator;
@override int get length => _m.length;
@override Set<String> toSet() => Tags()..addAll(this);
}
void main() {
final t = Tags()..addAll(['first', 'second', 'third']);
print('elementAt(1): ${t.elementAt(1)}');
print('walks the iterator; no index storage needed');
}elementAt(1): second walks the iterator; no index storage needed
UnmodifiableSetView
class UnmodifiableSetView<E> extends SetBase<E> with _UnmodifiableSetMixin<E>
An unmodifiable Set view of another Set.
Methods that could change the set, such as add and remove, must not be called.
final baseSet = <String>{'Mars', 'Mercury', 'Earth', 'Venus'};
final unmodifiableSetView = UnmodifiableSetView(baseSet);
// Remove an element from the original set.
baseSet.remove('Venus');
print(unmodifiableSetView); // {Mars, Mercury, Earth}
unmodifiableSetView.remove('Earth'); // Throws.import 'raya:collection';
void main() {
final tags = {'news', 'sport'};
final readOnly = UnmodifiableSetView(tags);
print('view: $readOnly, contains sport ${readOnly.contains('sport')}');
tags.add('weather');
print('backing set changed, view sees it: $readOnly');
try {
readOnly.add('x');
} on UnsupportedError {
print('readOnly.add -> UnsupportedError');
}
}view: {news, sport}, contains sport true
backing set changed, view sees it: {news, sport, weather}
readOnly.add -> UnsupportedErrorConstructors
UnmodifiableSetView(Set<E> source)Creates an UnmodifiableSetView of source.
import 'raya:collection';
void main() {
final view = UnmodifiableSetView({1, 2, 3});
print('length ${view.length}, union with {4}: ${view.union({4})}');
try {
view.remove(1);
} on UnsupportedError {
print('remove -> UnsupportedError');
}
}length 3, union with {4}: {1, 2, 3, 4}
remove -> UnsupportedErrorProperties
int get lengthIterator<E> get iteratorMethods
bool contains(Object? element)import 'raya:collection';
void main() {
final view = UnmodifiableSetView({'a', 'b'});
print('contains("a"): ${view.contains('a')}, contains("z"): ${view.contains('z')}');
}contains("a"): true, contains("z"): falseE? lookup(Object? element)import 'raya:collection';
void main() {
final view = UnmodifiableSetView({'alpha', 'beta'});
print('lookup("beta"): ${view.lookup('beta')}, lookup("gamma"): ${view.lookup('gamma')}');
}lookup("beta"): beta, lookup("gamma"): nullSet<E> toSet()import 'raya:collection';
void main() {
final view = UnmodifiableSetView({1, 2});
final copy = view.toSet()..add(3);
print('toSet gives a mutable copy: $copy, view still $view');
}toSet gives a mutable copy: {1, 2, 3}, view still {1, 2}SplayTreeMap
final class SplayTreeMap<K, V> extends _SplayTree<K, _SplayTreeMapNode<K, V>> with MapMixin<K, V>
A Map of objects that can be ordered relative to each other.
The map is based on a self-balancing binary tree. It allows most single-entry operations in amortized logarithmic time.
Keys of the map are compared using the compare function passed in the constructor, both for ordering and for equality. If the map contains only the key a, then map.containsKey(b) will return true if and only if compare(a, b) == 0, and the value of a == b is not even checked. If the compare function is omitted, the objects are assumed to be Comparable, and are compared using their Comparable.compareTo method. Non-comparable objects (including null) will not work as keys in that case.
To allow calling [operator []], remove or containsKey with objects that are not supported by the compare function, an extra isValidKey predicate function can be supplied. This function is tested before using the compare function on an argument value that may not be a K value. If omitted, the isValidKey function defaults to testing if the value is a K.
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).
Example:
final planetsByMass = SplayTreeMap<double, String>((a, b) => a.compareTo(b));
To add data to a map, use [operator[]=], addAll or addEntries.
planetsByMass[0.06] = 'Mercury';
planetsByMass
.addAll({0.81: 'Venus', 1.0: 'Earth', 0.11: 'Mars', 317.83: 'Jupiter'});
To check if the map is empty, use isEmpty or isNotEmpty. To find the number of map entries, use length.
print(planetsByMass.isEmpty); // false
print(planetsByMass.length); // 5
The forEach method calls a function for each key/value entry of the map.
planetsByMass.forEach((key, value) {
print('$key \t $value');
// 0.06 Mercury
// 0.11 Mars
// 0.81 Venus
// 1.0 Earth
// 317.83 Jupiter
});
To check whether the map has an entry with a specific key, use containsKey.
final keyOneExists = planetsByMass.containsKey(1.0); // true
final keyFiveExists = planetsByMass.containsKey(5); // false
To check whether the map has an entry with a specific value, use containsValue.
final earthExists = planetsByMass.containsValue('Earth'); // true
final plutoExists = planetsByMass.containsValue('Pluto'); // false
To remove an entry with a specific key, use remove.
final removedValue = planetsByMass.remove(1.0);
print(removedValue); // Earth
To remove multiple entries at the same time, based on their keys and values, use removeWhere.
planetsByMass.removeWhere((key, value) => key <= 1);
print(planetsByMass); // {317.83: 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.
planetsByMass.update(1, (v) => '', ifAbsent: () => 'Earth');
planetsByMass.putIfAbsent(317.83, () => 'Another Jupiter');
print(planetsByMass); // {1.0: Earth, 317.83: Jupiter}
To update the values of all keys, based on the existing key and value, use updateAll.
planetsByMass.updateAll((key, value) => 'X');
print(planetsByMass); // {1.0: X, 317.83: X}
To remove all entries and empty the map, use clear.
planetsByMass.clear();
print(planetsByMass.isEmpty); // false
print(planetsByMass); // {}
See also:
Map, the general interface of key/value pair collections.HashMapis unordered (the order of iteration is not guaranteed).LinkedHashMapiterates in key insertion order.
import 'raya:collection';
void main() {
final m = SplayTreeMap<String, int>();
m['pear'] = 3;
m['apple'] = 7;
m['fig'] = 1;
print('sorted by key: $m');
print('firstKey ${m.firstKey()}, lastKey ${m.lastKey()}');
print('key after "b": ${m.firstKeyAfter('b')}');
print('key before "g": ${m.lastKeyBefore('g')}');
}sorted by key: {apple: 7, fig: 1, pear: 3}
firstKey apple, lastKey pear
key after "b": fig
key before "g": figConstructors
SplayTreeMap([int Function(K key1, K key2)? compare, bool Function(dynamic potentialKey)? isValidKey])import 'raya:collection';
void main() {
// A custom order: by length, then alphabetically.
final m = SplayTreeMap<String, int>((a, b) => a.length != b.length ? a.length - b.length : a.compareTo(b));
for (final w in ['banana', 'kiwi', 'fig', 'apple', 'date']) {
m[w] = w.length;
}
print(m.keys.toList());
}[fig, date, kiwi, apple, banana]
factory SplayTreeMap.from(Map<Object?, Object?> other, [int Function(K key1, K key2)? compare, bool Function(dynamic potentialKey)? isValidKey])Creates a SplayTreeMap that contains all key/value pairs of other.
The keys must all be instances of K and the values of V. The other map itself can have any type. Example:
final baseMap = <int, Object>{3: 'C', 1: 'A', 2: 'B'};
final fromBaseMap = SplayTreeMap<int, String>.from(baseMap);
print(fromBaseMap); // {1: A, 2: B, 3: C}import 'raya:collection';
void main() {
final Map<Object?, Object?> raw = {'pear': 3, 'apple': 1, 'fig': 2};
final m = SplayTreeMap<String, int>.from(raw);
print('sorted by key: $m');
}sorted by key: {apple: 1, fig: 2, pear: 3}factory SplayTreeMap.of(Map<K, V> other, [int Function(K key1, K key2)? compare, bool Function(dynamic potentialKey)? isValidKey])Creates a SplayTreeMap that contains all key/value pairs of other. Example:
final baseMap = <int, String>{3: 'A', 2: 'B', 1: 'C', 4: 'D'};
final mapOf = SplayTreeMap<num, Object>.of(baseMap);
print(mapOf); // {1: C, 2: B, 3: A, 4: D}import 'raya:collection';
void main() {
final byLength = SplayTreeMap<String, int>.of(
{'banana': 6, 'kiwi': 4, 'fig': 3}, (a, b) => a.length.compareTo(b.length));
print('ordered by key length: $byLength');
}ordered by key length: {fig: 3, kiwi: 4, banana: 6}factory SplayTreeMap.fromIterable(Iterable iterable, {K Function(dynamic element)? key, V Function(dynamic element)? value, int Function(K key1, K key2)? compare, bool Function(dynamic potentialKey)? isValidKey})Creates a SplayTreeMap 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 functions are specified for key and value, the default is to use the iterable value itself. Example:
final numbers = [12, 11, 14, 13];
final mapFromIterable =
SplayTreeMap<int, int>.fromIterable(numbers,
key: (i) => i, value: (i) => i * i);
print(mapFromIterable); // {11: 121, 12: 144, 13: 169, 14: 196}import 'raya:collection';
void main() {
final m = SplayTreeMap<int, String>.fromIterable(['ccc', 'a', 'bb'],
key: (s) => (s as String).length, value: (s) => s as String);
print('keyed by length, sorted: $m');
}keyed by length, sorted: {1: a, 2: bb, 3: ccc}factory SplayTreeMap.fromIterables(Iterable<K> keys, Iterable<V> values, [int Function(K key1, K key2)? compare, bool Function(dynamic potentialKey)? isValidKey])Creates a SplayTreeMap 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 keys = ['1', '2', '3', '4'];
final values = ['A', 'B', 'C', 'D'];
final mapFromIterables = SplayTreeMap.fromIterables(keys, values);
print(mapFromIterables); // {1: A, 2: B, 3: C, 4: D}import 'raya:collection';
void main() {
final m = SplayTreeMap.fromIterables([30, 10, 20], ['thirty', 'ten', 'twenty']);
print('sorted: $m');
}sorted: {10: ten, 20: twenty, 30: thirty}Properties
bool get isEmptybool get isNotEmptyint get lengthIterable<K> get keysIterable<V> get valuesIterable<MapEntry<K, V>> get entriesMethods
V? remove(Object? key)import 'raya:collection';
void main() {
final m = SplayTreeMap.of({1: 'a', 2: 'b', 3: 'c'});
print('remove(2): ${m.remove(2)} -> $m');
print('remove(9): ${m.remove(9)}');
}remove(2): b -> {1: a, 3: c}
remove(9): nullV putIfAbsent(K key, V ifAbsent())import 'raya:collection';
void main() {
final m = SplayTreeMap<String, int>();
for (final w in 'the cat and the hat'.split(' ')) {
m.putIfAbsent(w, () => m.length);
}
print('first-seen index per word (sorted by word): $m');
}first-seen index per word (sorted by word): {and: 2, cat: 1, hat: 3, the: 0}V update(K key, V update(V value), {V Function()? ifAbsent})import 'raya:collection';
void main() {
final counts = SplayTreeMap<String, int>();
for (final c in 'banana'.split('')) {
counts.update(c, (n) => n + 1, ifAbsent: () => 1);
}
print('letter counts: $counts');
}letter counts: {a: 3, b: 1, n: 2}void updateAll(V update(K key, V value))import 'raya:collection';
void main() {
final prices = SplayTreeMap.of({'tea': 2.0, 'cake': 3.5});
prices.updateAll((k, v) => v * 1.1);
print('plus 10%: ${prices.map((k, v) => MapEntry(k, v.toStringAsFixed(2)))}');
}plus 10%: {cake: 3.85, tea: 2.20}void addAll(Map<K, V> other)import 'raya:collection';
void main() {
final m = SplayTreeMap.of({5: 'e'});
m.addAll({1: 'a', 3: 'c'});
print('addAll keeps keys sorted: $m');
}addAll keeps keys sorted: {1: a, 3: c, 5: e}void forEach(void f(K key, V value))import 'raya:collection';
void main() {
final m = SplayTreeMap.of({'b': 2, 'c': 3, 'a': 1});
m.forEach((k, v) => print('$k = $v'));
}a = 1 b = 2 c = 3
void clear()import 'raya:collection';
void main() {
final m = SplayTreeMap.of({1: 1})..clear();
print('after clear: $m, firstKey ${m.firstKey()}');
}after clear: {}, firstKey nullbool containsKey(Object? key)import 'raya:collection';
void main() {
final m = SplayTreeMap.of({1: 'a', 2: 'b'});
print('containsKey(1): ${m.containsKey(1)}, containsKey(3): ${m.containsKey(3)}');
}containsKey(1): true, containsKey(3): false
bool containsValue(Object? value)import 'raya:collection';
void main() {
final m = SplayTreeMap.of({1: 'a', 2: 'b'});
print('containsValue("b"): ${m.containsValue('b')} (scans all values)');
}containsValue("b"): true (scans all values)K? firstKey()The first key in the map.
Returns null if the map is empty.
import 'raya:collection';
void main() {
final m = SplayTreeMap.of({'m': 1, 'c': 2, 'x': 3});
print('firstKey: ${m.firstKey()}');
print('empty map firstKey: ${SplayTreeMap<int, int>().firstKey()}');
}firstKey: c empty map firstKey: null
K? lastKey()The last key in the map.
Returns null if the map is empty.
import 'raya:collection';
void main() {
final m = SplayTreeMap.of({3: 'c', 9: 'i', 1: 'a'});
print('lastKey: ${m.lastKey()} -> ${m[m.lastKey()]}');
}lastKey: 9 -> i
K? lastKeyBefore(K key)The last key in the map that is strictly smaller than key.
Returns null if such a key was not found.
import 'raya:collection';
void main() {
// Tax bracket lookup: the bracket is the largest threshold below the income.
final brackets = SplayTreeMap.of({0: '10%', 11000: '12%', 44725: '22%', 95375: '24%'});
for (final income in [5000, 44725, 60000]) {
final key = brackets.containsKey(income) ? income : brackets.lastKeyBefore(income)!;
print('income $income -> ${brackets[key]}');
}
print('lastKeyBefore(0): ${brackets.lastKeyBefore(0)}');
}income 5000 -> 10% income 44725 -> 22% income 60000 -> 22% lastKeyBefore(0): null
K? firstKeyAfter(K key)Get the first key in the map that is strictly larger than key. Returns null if such a key was not found.
import 'raya:collection';
void main() {
final schedule = SplayTreeMap.of({9: 'standup', 13: 'review', 16: 'demo'});
final now = 10;
final next = schedule.firstKeyAfter(now);
print('next after $now:00 -> $next:00 ${schedule[next]}');
print('after 16: ${schedule.firstKeyAfter(16)}');
}next after 10:00 -> 13:00 review after 16: null
Operators
V? operator [](Object? key)import 'raya:collection';
void main() {
final m = SplayTreeMap.of({'a': 1});
print('m["a"] = ${m['a']}, m["z"] = ${m['z']}');
}m["a"] = 1, m["z"] = null
void operator []=(K key, V value)import 'raya:collection';
void main() {
final m = SplayTreeMap<int, String>();
m[3] = 'c';
m[1] = 'a';
m[2] = 'b';
print('inserted 3,1,2 -> $m');
}inserted 3,1,2 -> {1: a, 2: b, 3: c}SplayTreeSet
final class SplayTreeSet<E> extends _SplayTree<E, _SplayTreeSetNode<E>> with Iterable<E>, SetMixin<E>
A Set of objects that can be ordered relative to each other.
The set is based on a self-balancing binary tree. It allows most operations in amortized logarithmic time.
Elements of the set are compared using the compare function passed in the constructor, both for ordering and for equality. If the set contains only an object a, then set.contains(b) will return true if and only if compare(a, b) == 0, and the value of a == b is not even checked. If the compare function is omitted, the objects are assumed to be Comparable, and are compared using their Comparable.compareTo method. Non-comparable objects (including null) will not work as an element in that case.
Note: Do not modify a set (add or remove elements) while an operation is being performed on that set, for example in functions called during a forEach or containsAll call, or while iterating the set.
Do not modify elements in a way which changes their equality (and thus their hash code) while they are in the set. Some specialized kinds of sets may be more permissive with regards to equality, in which case they should document their different behavior and restrictions.
Example:
final planets = SplayTreeSet<String>((a, b) => a.compareTo(b));
To add data to a set, use add or addAll.
planets.add('Neptune');
planets.addAll({'Venus', 'Mars', 'Earth', 'Jupiter'});
print(planets); // {Earth, Jupiter, Mars, Neptune, Venus}
To check if the set is empty, use isEmpty or isNotEmpty. To find the number of elements in the set, use length.
final isEmpty = planets.isEmpty; // false
final length = planets.length; // 5
To check whether the set contains a specific element, use contains.
final marsExists = planets.contains('Mars'); // true
To get element value using index, use elementAt.
final elementAt = planets.elementAt(1);
print(elementAt); // Jupiter
To make a copy of set, use toSet.
final copySet = planets.toSet(); // a `SplayTreeSet` with the same ordering.
print(copySet); // {Earth, Jupiter, Mars, Neptune, Venus}
To remove an element, use remove.
final removedValue = planets.remove('Mars'); // true
print(planets); // {Earth, Jupiter, Neptune, Venus}
To remove multiple elements at the same time, use removeWhere.
planets.removeWhere((element) => element.startsWith('J'));
print(planets); // {Earth, Neptune, Venus}
To removes all elements in this set that do not meet a condition, use retainWhere.
planets.retainWhere((element) => element.contains('Earth'));
print(planets); // {Earth}
To remove all elements and empty the set, use clear.
planets.clear();
print(planets.isEmpty); // true
print(planets); // {}
See also:
Setis a base-class for collection of objects.HashSetthe order of the objects in the iterations is not guaranteed.LinkedHashSetobjects stored based on insertion order.
import 'raya:collection';
void main() {
final s = SplayTreeSet<int>.from([5, 1, 9, 3, 7, 3]);
print('sorted set: $s');
print('first ${s.first}, last ${s.last}');
s.removeWhere((x) => x > 6);
print('without > 6: $s');
}sorted set: {1, 3, 5, 7, 9}
first 1, last 9
without > 6: {1, 3, 5}Constructors
SplayTreeSet([int Function(E key1, E key2)? compare, bool Function(dynamic potentialKey)? isValidKey])Create a new SplayTreeSet with the given compare function.
If the compare function is omitted, it defaults to Comparable.compare, and the elements must be comparable.
A provided compare function may not work on all objects. It may not even work on all E instances.
For operations that add elements to the set, the user is supposed to not pass in objects that don't work with the compare function.
The methods contains, remove, lookup, removeAll or retainAll are typed to accept any object(s), and the isValidKey test can used to filter those objects before handing them to the compare function.
If isValidKey is provided, only values satisfying isValidKey(other) are compared using the compare method in the methods mentioned above. If the isValidKey function returns false for an object, it is assumed to not be in the set.
If omitted, the isValidKey function defaults to checking against the type parameter: other is E.
import 'raya:collection';
void main() {
final s = SplayTreeSet<int>()..addAll([5, 1, 4, 1, 3]);
print('sorted, unique: $s');
final desc = SplayTreeSet<int>((a, b) => b.compareTo(a))..addAll([5, 1, 4]);
print('custom compare (descending): $desc');
}sorted, unique: {1, 3, 4, 5}
custom compare (descending): {5, 4, 1}factory SplayTreeSet.from(Iterable elements, [int Function(E key1, E key2)? compare, bool Function(dynamic potentialKey)? isValidKey])Creates a SplayTreeSet that contains all elements.
The set works as if created by SplayTreeSet<E>(compare, isValidKey).
All the elements should be instances of E and valid arguments to compare. The elements iterable itself may have any element type, so this constructor can be used to down-cast a Set, for example as:
Set<SuperType> superSet = ...;
Set<SubType> subSet =
SplayTreeSet<SubType>.from(superSet.whereType<SubType>());
Example:
final numbers = <num>[20, 30, 10];
final setFrom = SplayTreeSet<int>.from(numbers);
print(setFrom); // {10, 20, 30}import 'raya:collection';
void main() {
final Iterable<dynamic> raw = ['b', 'c', 'a'];
print('from: ${SplayTreeSet<String>.from(raw)}');
}from: {a, b, c}factory SplayTreeSet.of(Iterable<E> elements, [int Function(E key1, E key2)? compare, bool Function(dynamic potentialKey)? isValidKey])Creates a SplayTreeSet from elements.
The set works as if created by new SplayTreeSet<E>(compare, isValidKey).
All the elements should be valid as arguments to the compare function. Example:
final baseSet = <int>{1, 2, 3};
final setOf = SplayTreeSet<num>.of(baseSet);
print(setOf); // {1, 2, 3}import 'raya:collection';
void main() {
final s = SplayTreeSet.of(['Banana', 'apple', 'Cherry'], (a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print('case-insensitive order: $s');
}case-insensitive order: {apple, Banana, Cherry}Properties
Iterator<E> get iteratorint get lengthbool get isEmptybool get isNotEmptyE get firstE get lastE get singleMethods
Set<R> cast<R>()import 'raya:collection';
void main() {
final SplayTreeSet<num> s = SplayTreeSet.of(<num>[3, 1, 2]);
final ints = s.cast<int>();
print('cast<int>: ${ints.toList()}, max ${ints.last}');
}cast<int>: [1, 2, 3], max 3
bool contains(Object? element)import 'raya:collection';
void main() {
final s = SplayTreeSet.of([10, 20, 30]);
print('contains(20): ${s.contains(20)}, contains(25): ${s.contains(25)}');
}contains(20): true, contains(25): false
bool add(E element)import 'raya:collection';
void main() {
final s = SplayTreeSet<String>();
print('add("m"): ${s.add('m')}, add("a"): ${s.add('a')}, add("m") again: ${s.add('m')}');
print('set: $s');
}add("m"): true, add("a"): true, add("m") again: false
set: {a, m}bool remove(Object? object)import 'raya:collection';
void main() {
final s = SplayTreeSet.of([1, 2, 3]);
print('remove(2): ${s.remove(2)}, remove(9): ${s.remove(9)}, set $s');
}remove(2): true, remove(9): false, set {1, 3}void addAll(Iterable<E> elements)import 'raya:collection';
void main() {
final s = SplayTreeSet.of([5]);
s.addAll([3, 9, 3, 1]);
print('after addAll: $s');
}after addAll: {1, 3, 5, 9}void removeAll(Iterable<Object?> elements)import 'raya:collection';
void main() {
final s = SplayTreeSet.of(List.generate(10, (i) => i));
s.removeAll([0, 2, 4, 6, 8]);
print('odds left: $s');
}odds left: {1, 3, 5, 7, 9}void retainAll(Iterable<Object?> elements)import 'raya:collection';
void main() {
final s = SplayTreeSet.of(['a', 'b', 'c', 'd']);
s.retainAll(['b', 'd', 'z']);
print('retained: $s');
}retained: {b, d}E? lookup(Object? object)import 'raya:collection';
void main() {
final s = SplayTreeSet<String>((a, b) => a.toLowerCase().compareTo(b.toLowerCase()))..add('Raya');
print('lookup("RAYA") returns the stored value: ${s.lookup('RAYA')}');
print('lookup("none"): ${s.lookup('none')}');
}lookup("RAYA") returns the stored value: Raya
lookup("none"): nullSet<E> intersection(Set<Object?> other)import 'raya:collection';
void main() {
final a = SplayTreeSet.of([1, 2, 3, 4]);
print('intersection: ${a.intersection({3, 4, 5})}');
}intersection: {3, 4}Set<E> difference(Set<Object?> other)import 'raya:collection';
void main() {
final a = SplayTreeSet.of([1, 2, 3, 4]);
print('difference: ${a.difference({2, 4})}');
}difference: {1, 3}Set<E> union(Set<E> other)import 'raya:collection';
void main() {
final a = SplayTreeSet.of([5, 1]);
print('union (still sorted): ${a.union({3, 7})}');
}union (still sorted): {1, 3, 5, 7}void clear()import 'raya:collection';
void main() {
final s = SplayTreeSet.of([1, 2])..clear();
print('after clear: $s');
}after clear: {}Set<E> toSet()import 'raya:collection';
void main() {
final s = SplayTreeSet.of([3, 1, 2]);
final copy = s.toSet()..add(0);
print('copy: $copy, original: $s, copy is SplayTreeSet: ${copy is SplayTreeSet}');
}copy: {0, 1, 2, 3}, original: {1, 2, 3}, copy is SplayTreeSet: trueString toString()import 'raya:collection';
void main() {
print('toString: ${SplayTreeSet.of(['b', 'a']).toString()}');
}toString: {a, b}class DoubleLinkedQueueEntry<E>
An entry in a doubly linked list.
Such an entry contains an element and a link to the previous or next entries, if any.
import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of(['a', 'c']);
final a = q.firstEntry()!;
a.append('b');
print('after append: $q');
final c = q.lastEntry()!;
print('c.previous = ${c.previousEntry()?.element}, c.next = ${c.nextEntry()?.element}');
}after append: {a, b, c}
c.previous = b, c.next = nullConstructors
DoubleLinkedQueueEntry(this.element)Creates a new entry with the given element.
import 'raya:collection';
void main() {
final e = DoubleLinkedQueueEntry<int>(42);
print('standalone entry: ${e.element}');
print('no neighbours: previous ${e.previousEntry()}, next ${e.nextEntry()}');
}standalone entry: 42 no neighbours: previous null, next null
Properties
Methods
void append(E e)Appends the given element e as entry just after this entry.
import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of([1, 3]);
q.firstEntry()!.append(2);
print('append after first: $q');
}append after first: {1, 2, 3}void prepend(E e)Prepends the given e as entry just before this entry.
import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of([2, 3]);
q.firstEntry()!.prepend(1);
print('prepend before first: $q');
}prepend before first: {1, 2, 3}E remove()Removes this entry from any chain of entries it is part of.
Returns its element value.
import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of(['a', 'b', 'c']);
final b = q.firstEntry()!.nextEntry()!;
print('remove returns ${b.remove()}, queue $q');
}remove returns b, queue {a, c}DoubleLinkedQueueEntry<E>? previousEntry()The previous entry, or null if there is none.
import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of([1, 2, 3]);
final out = <int>[];
for (var e = q.lastEntry(); e != null; e = e.previousEntry()) {
out.add(e.element);
}
print('walked backwards: $out');
}walked backwards: [3, 2, 1]
DoubleLinkedQueueEntry<E>? nextEntry()The next entry, or null if there is none.
import 'raya:collection';
void main() {
final q = DoubleLinkedQueue.of([1, 2, 3]);
for (var e = q.firstEntry(); e != null; e = e.nextEntry()) {
e.element *= 10;
}
print('scaled in place: $q');
}scaled in place: {10, 20, 30}