### Print Sorted IMap Keys Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md This example demonstrates how to create an IMap that is sorted by keys and then print its keys in sorted order. ```dart /// Prints sorted: "1,2,4,9" var imap = {2: "a", 4: "x", 1: "z", 9: "k"}.lock; print(imap.keyList.join(",")); ``` -------------------------------- ### ISet Sorted Order Example Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates how to configure an ISet to iterate in sorted order. Prints: "1,2,3,4,9". ```dart var iset = {2, 4, 1, 9, 3}.lock.withConfig(ConfigSet(sort: true)); print(iset.join(",")); ``` -------------------------------- ### Print Unsorted IMap Keys with Custom Config Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md This example shows how to create an IMap with a specific configuration to maintain insertion order (sort: false) and then print its keys. ```dart /// Prints in any order: "2,4,1,9" var imap = {2: "a", 4: "x", 1: "z", 9: "k"}.lock.withConfig(ConfigMap(sort: false)); print(imap.keyList.join(",")); ``` -------------------------------- ### ISet Insertion Order Example Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Shows how an ISet maintains insertion order by default. Prints: "2,4,1,9,3". ```dart var iset = {2, 4, 1, 9, 3}.lock; print(iset.join(",")); ``` -------------------------------- ### Create Const IList Instances Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Provides examples of correctly creating constant `IList` instances using `IList.empty()` or `IListConst` with the `const` keyword. ```dart const IList ilist1 = IList.empty(); const IList ilist2 = IListConst([]); const IList ilist3 = IListConst([1, 2, 3]); const IList ilist4 = IListConst([1, 2], ConfigList(isDeepEquals: false)); ``` -------------------------------- ### Global IList Configuration Example Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates changing the global default configuration for IList to use identity-equals and turn off hashCode caching. Note that this affects lists created after the configuration change. ```dart var list = [1, 2]; /// The default is deep-equals. var ilistA1 = IList(list); var ilistA2 = IList(list); print(ilistA1 == ilistA2); // True! /// Now we change the default to identity-equals, and hashCode cache off. /// This will affect lists created from now on. defaultConfig = ConfigList(isDeepEquals: false, cacheHashCode: false); var ilistB1 = IList(list); var ilistB2 = IList(list); print(ilistB1 == ilistB2); // False! /// Configuration changes don't affect existing lists. print(ilistA1 == ilistA2); // True! ``` -------------------------------- ### Incorrect Const IMap Instantiation Examples Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md These examples demonstrate incorrect ways to create const IMaps, such as omitting the 'const' keyword, not explicitly assigning to 'IMap', or attempting to create a non-empty sorted const map. ```dart // Wrong: Not using the const keyword. IMap imap = IMapConst({}); IMap imap = IMap.empty(); // Wrong: Not explicitly assigning it to an `IMap`. const imap = IMapConst({}); // Wrong: Const sorted map is not empty. const IMap imap = IMapConst({1, 2}, ConfigMap(sort: true)); ``` -------------------------------- ### IMapOfSets Real-world Usage: Courses to Students Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt A practical example demonstrating the use of IMapOfSets to manage student enrollments per course. It includes methods for enrolling and dropping students, and retrieving the list of students for a given course. ```dart // --- Real-world usage: courses → students --- class StudentsPerCourse { final IMapOfSets _data; StudentsPerCourse([Map>? data]) : _data = (data ?? {}).lock; StudentsPerCourse._raw(this._data); StudentsPerCourse enroll(String course, String student) => StudentsPerCourse._raw(_data.add(course, student)); StudentsPerCourse drop(String course, String student) => StudentsPerCourse._raw(_data.remove(course, student)); ISet studentsIn(String course) => _data.get(course) ?? ISet(); } ``` -------------------------------- ### IMapOfSets Query Operations Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Illustrates common query operations for IMapOfSets, including retrieving a set for a key, checking for key or value existence, and getting counts or collections of keys and values. ```dart // --- Query --- ISet? setA = m.get('a'); bool hasKey = m.containsKey('a'); bool hasVal = m.containsValue(2); int numKeys = m.lengthOfKeys; int uniqueVals = m.lengthOfNonRepeatingValues; ISet keys = m.keysAsSet; ISet vals = m.valuesAsSet; ``` -------------------------------- ### Generate IList with iterate and iterateWhile Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Illustrates generating an IList using `IList.iterate` for a fixed number of elements based on a starting value and a transformation function, and `IList.iterateWhile` for generating elements until a condition is met. ```dart IList powers = IList.iterate(1, 5, (n) => n * 2); print(powers); // [1, 2, 4, 8, 16] IList whileList = IList.iterateWhile(1, (n) => n < 100, (n) => n * 3); print(whileList); // [1, 3, 9, 27, 81, 243] ``` -------------------------------- ### Compute Length with Immutable Map Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md This example demonstrates a function that accepts an IMap, guaranteeing that the map will not be modified. This improves code clarity and predictability, as both caller and callee know the data remains unchanged. ```dart int computeLength(IMap responseMap) { // ... computes length without mutation ... } ``` -------------------------------- ### Create and Use ListSet Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Shows how to create a ListSet from an initial list and demonstrates its dual nature as both a List and a Set. ```Dart ListSet listSet = ListSet.of([1, 2, 3]); expect(listSet[2], 3); expect(listSet.contains(2), isTrue); List list = listSet; Set set = listSet; expect(list[2], 3); expect(set.contains(2), isTrue); ``` -------------------------------- ### ISet Construction and Basic Usage Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Demonstrates various ways to construct an ISet, including from existing collections and using constants. Shows how to create a sorted ISet. ```dart import 'package:fast_immutable_collections/fast_immutable_collections.dart'; // --- Construction --- ISet a = ISet({1, 2, 3}); ISet b = {1, 2, 3}.lock; ISet c = [1, 2, 2, 3].toISet(); // duplicates removed const ISet d = ISet.empty(); const ISet e = ISetConst({1, 2, 3}); // --- Sorted set --- ISet sorted = {3, 1, 2}.lock.withConfig(const ConfigSet(sort: true)); print(sorted.join(',')); // 1,2,3 ``` -------------------------------- ### Run Dart Benchmarks Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Execute benchmarks using pure Dart. Ensure you are in the project's root directory. ```bash dart benchmark/lib/src/benchmarks.dart ``` -------------------------------- ### IMap.orNull Usage Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Example of using IMap.orNull to safely create an IMap from a nullable Map, defaulting to an empty IMap if null. ```dart // --- IMap.orNull --- class AppState { final IMap scores; AppState({Map? scores}) : scores = IMap.orNull(scores) ?? const IMap.empty(); } ``` -------------------------------- ### ISet Global Configuration Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Demonstrates setting global default configurations for ISet and flushing factor. ```dart ISet.defaultConfig = const ConfigSet(isDeepEquals: true, sort: true, cacheHashCode: true); ISet.flushFactor = 50; ``` -------------------------------- ### Define a Student Class Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md A basic Dart class representing a student, implementing Comparable for sorting. Ensure this class is defined before use in collection examples. ```dart class Student implements Comparable{ final String name; Student(this.name); String toString() => name; bool operator ==(Object other) => identical(this, other) || other is Student && runtimeType == other.runtimeType && name == other.name; int get hashCode => name.hashCode; @override int compareTo(Student other) => name.compareTo(other.name); } ``` -------------------------------- ### Create IList Instances Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates multiple ways to construct an IList, including using the constructor, locking a regular list, locking other iterables, and creating an empty IList. ```dart /// Ways to build an IList // Using the IList constructor IList ilist = IList([1, 2]); // Locking a regular list IList ilist = [1, 2].lock; // Locking a set as list IList ilist = {1, 2}.toIList(); // Creating an empty IList IList ilist = const IList.empty(); ``` -------------------------------- ### IList.orNull for CopyWith Patterns Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Provides an example of using `IList.orNull` within a `copyWith` method to handle optional iterable arguments, defaulting to an empty IList if null. ```dart class NotesState { final IList notes; NotesState({Iterable? notes}) : notes = IList.orNull(notes) ?? const IList.empty(); NotesState copyWith({Iterable? notes}) => NotesState(notes: IList.orNull(notes) ?? this.notes); } final state = NotesState(notes: ['a', 'b']); final updated = state.copyWith(notes: ['a', 'b', 'c']); print(updated.notes); // IList[a, b, c] ``` -------------------------------- ### Construct IList Instances Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Demonstrates various ways to create IList instances, including from iterables, using extensions, unsafe locking, and constant empty or pre-filled lists. ```dart IList a = IList([1, 2, 3]); // from iterable IList b = [1, 2, 3].lock; // via extension IList c = [1, 2, 3].lockUnsafe; // fast, no defensive copy const IList d = IList.empty(); // const empty const IList e = IListConst([1, 2]); // const with values ``` -------------------------------- ### Define a Class with Immutable List for JSON Serialization Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Example of a Dart class using `IList` that is annotated with `@JsonSerializable` for automatic JSON conversion. Requires generated methods `_$MyClassFromJson` and `_$MyClassToJson`. ```dart @JsonSerializable() class MyClass { final IList myList; MyClass(this.myList); factory MyClass.fromJson(Map json) => _$MyClassFromJson(json); Map toJson() => _$MyClassToJson(this); } ``` -------------------------------- ### Create IMap using Constructor Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Illustrates creating an IMap by passing a regular map to its constructor. ```dart IMap imap = IMap({"a": 1, "b": 2}); ``` -------------------------------- ### Configuring Immutable Collections with ConfigList, ConfigSet, ConfigMap, ConfigMapOfSets Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Demonstrates how to use configuration objects to control equality semantics, hash-code caching, and sort order for various immutable collection types. Configuration can be applied per-instance or globally. ```dart import 'package:fast_immutable_collections/fast_immutable_collections.dart'; // --- ConfigList --- const config = ConfigList(isDeepEquals: false, cacheHashCode: false); IList identList = IList.withConfig([1, 2, 3], config); print(identList == [1, 2, 3].lock); // false (identity equals) // Per-instance toggle IList deep = [1, 2].lock.withDeepEquals; IList ident = [1, 2].lock.withIdentityEquals; print(deep == ident); // false (different config) // --- ConfigSet --- ISet insertion = {3,1,2}.lock; // keeps insertion order ISet sorted = {3,1,2}.lock.withConfig(const ConfigSet(sort: true)); print(insertion.join(',')); // 3,1,2 print(sorted.join(',')); // 1,2,3 // --- ConfigMap --- IMap unsorted = {2:'b',1:'a'}.lock; IMap sortedM = {2:'b',1:'a'}.lock.withConfig(const ConfigMap(sort: true)); print(unsorted.toKeyList()); // [2, 1] print(sortedM.toKeyList()); // [1, 2] // --- ConfigMapOfSets --- IMapOfSets mos = IMapOfSets.withConfig( {'a': {1,2}}, const ConfigMapOfSets( isDeepEquals: true, sortKeys: true, sortValues: true, removeEmptySets: true, cacheHashCode: true, ), ); // --- Global defaults (set once at app startup, then lock) --- IList.defaultConfig = const ConfigList(isDeepEquals: true, cacheHashCode: true); ISet.defaultConfig = const ConfigSet(sort: false); IMap.defaultConfig = const ConfigMap(sort: false, cacheHashCode: true); ImmutableCollection.autoFlush = true; ImmutableCollection.disallowUnsafeConstructors = true; ImmutableCollection.lockConfig(); // freezes all config — call at end of init ``` -------------------------------- ### Incorrect Const ISet Creation Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Examples of incorrect ways to create a const ISet, such as not using the const keyword, not explicitly assigning to ISet, or creating a non-empty const sorted set. ```dart // Wrong: Not using the const keyword. ISet iset = ISetConst({}); ISet iset = ISet.empty(); // Wrong: Not explicitly assigning it to an `ISet`. const iset = ISetConst({}); // Wrong: Const sorted set is not empty. const ISet iset = ISetConst({1, 2}, ConfigSet(sort: true)); ``` -------------------------------- ### Creating IList with Specific Configuration Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Shows how to use the `IList.withConfig` constructor to initialize an IList with a desired equality configuration (deep or identity). ```dart var list = [1, 2]; var ilist1 = IList.withConfig(list, ConfigList(isDeepEquals: true)); var ilist2 = IList.withConfig(list, ConfigList(isDeepEquals: false)); print(list.lock == ilist1); // True! print(list.lock == ilist2); // False! ``` -------------------------------- ### Compute Length with Mutable Map Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md This example shows a function that mutates a Map while computing its length. Using mutable collections can lead to unexpected side effects and makes code harder to reason about. ```dart int computeLength(Map responseMap) { // ... mutates responseMap in some tricky way ... } ``` -------------------------------- ### Create IMap from Values and Key Mapper Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates building an IMap using a list of values and a function to map each value to a key. Results in {3: "Jim", 5: "David"}. ```dart IMap imap = IMap.fromValues(keyMapper: (name) => name.length, values: ["Jim", "David"]); ``` -------------------------------- ### IMap Construction Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Illustrates different ways to construct an IMap, including from maps, using constants, and factory constructors. ```dart import 'package:fast_immutable_collections/fast_immutable_collections.dart'; // --- Construction --- IMap a = IMap({'a': 1, 'b': 2}); IMap b = {'a': 1, 'b': 2}.lock; const IMap c = IMap.empty(); const IMap d = IMapConst({'x': 10, 'y': 20}); // --- Factory constructors --- IMap fromKeys = IMap.fromKeys( keys: ['Jim', 'David'], valueMapper: (name) => name.length, ); // {'Jim': 3, 'David': 5} IMap fromValues = IMap.fromValues( keyMapper: (name) => name.length, values: ['Jim', 'David'], ); // {3: 'Jim', 5: 'David'} IMap fromIter = IMap.fromIterable( ['Jim', 'David'], keyMapper: (name) => name.toUpperCase(), valueMapper: (name) => name.length, ); // {'JIM': 3, 'DAVID': 5} IMap fromIterables = IMap.fromIterables(['a', 'b'], [1, 2]); ``` -------------------------------- ### Convert ISet to Set by unlocking Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Obtain a mutable `Set` from an `ISet` by using the `.unlock` extension property. This provides a direct way to get a mutable view of the immutable set's elements. ```dart Set set = iset.unlock; ``` -------------------------------- ### Create IMap from Keys and Value Mapper Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Illustrates building an IMap using a list of keys and a function to map each key to a value. Results in {"Jim": 3, "David": 5}. ```dart IMap imap = IMap.fromKeys(keys: ["Jim", "David"], valueMapper: (name) => name.length); ``` -------------------------------- ### Global IList Configuration Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Shows how to set global configuration options for IList, such as equality comparison and hash code caching, and how to lock these configurations to prevent further changes. ```dart IList.defaultConfig = const ConfigList(isDeepEquals: false, cacheHashCode: false); IList.flushFactor = 200; ImmutableCollection.lockConfig(); // lock — no further changes allowed ``` -------------------------------- ### Create IMap from Map Entries Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates creating an IMap from a list of MapEntry objects. ```dart IMap imap = IMap.fromEntries([MapEntry("a", 1), MapEntry("b", 2)]); ``` -------------------------------- ### Using IList as Map Keys for Caching Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Illustrates how IList's equality comparison allows them to be used as keys in a Map, enabling efficient caching of results. ```dart Map sumResult = {}; String getSum(int a, int b) { var keys = [a, b].lock; var sum = sumResult[keys]; if (sum != null) { return "Got from cache: $a + $b = $sum"; } else { sum = a + b; sumResult[keys] = sum; return "Newly calculated: $a + $b = $sum"; } } print(getSum(5, 3)); // Newly calculated: 5 + 3 = 8 print(getSum(8, 9)); // Newly calculated: 8 + 9 = 17 print(getSum(5, 3)); // Got from cache: 5 + 3 = 8 ``` -------------------------------- ### Create IMap by Locking a Regular Map Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Shows how to create an IMap by using the '.lock' extension method on a regular map. ```dart IMap imap = {"a": 1, "b": 2}.lock; ``` -------------------------------- ### StudentsPerCourse Class Implementation Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Provides a comprehensive implementation of a StudentsPerCourse class using IMapOfSets to manage student enrollments in courses. Includes methods for adding/removing students and courses, and retrieving course/student information. ```dart class StudentsPerCourse { final IMapOfSets imap; StudentsPerCourse([Map> studentsPerCourse]) : imap = (studentsPerCourse ?? {}).lock; StudentsPerCourse._(this.imap); ISet courses() => imap.keysAsSet; ISet students() => imap.valuesAsSet; IMapOfSets getCoursesPerStudent() => imap.invertKeysAndValues(); IList studentsInAlphabeticOrder() => imap.valuesAsSet.toIList(compare: (s1, s2) => s1.name.compareTo(s2.name)); IList studentNamesInAlphabeticOrder() => imap.valuesAsSet.map((s) => s.name).toIList(); StudentsPerCourse addStudentToCourse(Student student, Course course) => StudentsPerCourse._(imap.add(course, student)); StudentsPerCourse addStudentToCourses(Student student, Iterable courses) => StudentsPerCourse._(imap.addValuesToKeys(courses, [student])); StudentsPerCourse addStudentsToCourse(Iterable students, Course course) => StudentsPerCourse._(imap.addValues(course, students)); StudentsPerCourse addStudentsToCourses(Map> studentsPerCourse) => StudentsPerCourse._(imap.addMap(studentsPerCourse)); StudentsPerCourse removeStudentFromCourse(Student student, Course course) => StudentsPerCourse._(imap.remove(course, student)); StudentsPerCourse removeStudentFromAllCourses(Student student) => StudentsPerCourse._(imap.removeValues([student])); StudentsPerCourse removeCourse(Course course) => StudentsPerCourse._(imap.removeSet(course)); Map> toMap() => imap.unlock; int get numberOfCourses => imap.lengthOfKeys; int get numberOfStudents => imap.lengthOfNonRepeatingValues; } ``` -------------------------------- ### Creating IList from ISet with Sorting Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Shows how to convert an ISet to an IList, optionally sorting the elements during the conversion process. ```dart IList asList = ISet.fromIList( [3, 1, 2].lock, config: const ConfigSet(), ); IList sorted2 = IList.fromISet( {3, 1, 2}.lock, compare: (a, b) => a.compareTo(b), config: null, ); print(sorted2); // [1, 2, 3] ``` -------------------------------- ### Configuring IList Equality with withConfig Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates using the `withConfig` method with `ConfigList` to explicitly set the equality behavior (deep or identity) for an IList. ```dart var list = [1, 2]; var ilist1 = list.lock.withConfig(ConfigList(isDeepEquals: true)); var ilist2 = list.lock.withConfig(ConfigList(isDeepEquals: false)); print(list.lock == ilist1); // True! print(list.lock == ilist2); // False! ``` -------------------------------- ### Iterating and Converting IMap to Lists/Sets Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Demonstrates iterating over IMap entries and converting keys/values to IList or ISet. ```dart // --- Iterating --- for (final entry in m.entries) print('${entry.key}: ${entry.value}'); IList keys = m.toKeyIList(); IList values = m.toValueIList(); ISet keySet = m.toKeyISet(); ``` -------------------------------- ### Create an Empty IMap Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Shows how to create an empty, constant IMap. ```dart IMap imap = const IMap.empty(); ``` -------------------------------- ### Instantiate Const IMapOfSets Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates correct instantiation of a const IMapOfSets. Follow specific rules regarding const keyword, explicit assignment, and configuration for empty sets or sorted keys/values. ```Dart const IMap imap1 = IMapOfSetsConst(IMapConst({'a': ISetConst({1, 2})})); ``` ```Dart const IMap imap2 = IMapOfSetsConst(IMapConst({})); ``` ```Dart const IMap imap3 = IMapOfSetsConst(IMapConst({'a': ISetConst({})}, ConfigMapIfSets(removeEmptySets: false)); ``` ```Dart const IMap imap4 = IMapOfSetsConst(IMapConst({}), ConfigMapIfSets(sortKeys: true)); ``` -------------------------------- ### Configure IList for Identity Equals Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Demonstrates how to configure an IList to use identity-based equality comparison instead of deep element comparison. ```dart IList idList = [1, 2].lock.withIdentityEquals; print(idList == [1, 2].lock); // false (identity comparison) ``` -------------------------------- ### Create IMap from Key and Value Iterables Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Illustrates creating an IMap by providing separate Iterables for keys and values. Results in {"a": 1, "b": 2}. ```dart IMap imap = IMap.fromIterables(["a", "b"], [1, 2]); ``` -------------------------------- ### Sorted IMap Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Shows how to create and use a sorted IMap, where entries are ordered by key. ```dart // --- Sorted map --- IMap sorted2 = {2: 'b', 1: 'a', 3: 'c'}.lock .withConfig(const ConfigMap(sort: true)); print(sorted2.toKeyList().join(',')); // 1,2,3 ``` -------------------------------- ### Create a Custom Students Collection with FromIListMixin Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Implement a strongly-typed immutable collection of Students using FromIListMixin. This boilerplate code sets up the collection to wrap an IList. ```dart class Students with FromIListMixin { /// This is the boilerplate to create the collection: final IList _students; Students([Iterable students]) : _students = IList(students); Students newInstance(IList ilist) => Students(ilist); IList get ilist => _students; /// And then you can add your own specific methods: String greetings() => "Hello ${_students.join(", ")}."; } ``` -------------------------------- ### IMapOfSets Construction and Mutation Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Demonstrates how to construct and mutate an IMapOfSets, which is an immutable map where each key maps to an ISet of values. Construction can be done from a Map or by locking an existing Map. Mutation methods like add, addValues, remove, removeSet, and removeValues are shown. ```dart import 'package:fast_immutable_collections/fast_immutable_collections.dart'; // --- Construction --- IMapOfSets m = IMapOfSets({'a': {1, 2}, 'b': {3, 4}}); IMapOfSets locked = {'a': {1, 2}}.lock; // extension on Map> const IMapOfSets empty = IMapOfSetsConst(IMapConst({})); // --- Mutation --- m = m.add('a', 3); // {'a': {1,2,3}, 'b': {3,4}} m = m.addValues('a', [4, 5]); m = m.remove('a', 1); // remove value 1 from key 'a' m = m.removeSet('b'); // remove entire key m = m.removeValues([3]); // remove value 3 from ALL keys ``` -------------------------------- ### Run Flutter App in Release Mode Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/example/benchmark/benchmark_app/README.md Execute the Flutter application in release mode for accurate performance comparisons. Replace `` with your target device identifier. ```cmd flutter run -d --release ``` -------------------------------- ### ISet Equality and Unlocking Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Demonstrates how ISet equality is checked (unordered deep equals) and how to unlock an ISet back into a mutable Set. ```dart print({1,2,3}.lock == {3,2,1}.lock); // true (unordered deep equals) // --- Unlock --- Set mutable = s.unlock; Set view = s.unlockView; Set lazy = s.unlockLazy; ``` -------------------------------- ### Configuring IList for Identity Equality Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Shows how to create an IList that compares its elements by identity instead of deep equality using the `withIdentityEquals` getter. ```dart var ilist = [1, 2].lock; var ilist1 = [1, 2].lock; // By default use deep equals. var ilist2 = ilist.withIdentityEquals; // Change it to identity equals. var ilist3 = ilist2.withDeepEquals; // Change it back to deep equals. print(ilist == ilist1); // True! print(ilist == ilist2); // False! print(ilist == ilist3); // True! ``` -------------------------------- ### Use the Custom Students Collection Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates adding elements to the custom Students collection and calling its specific methods. Most IList methods are inherited and available. ```dart var james = Student("James"); var sara = Student("Sara"); var lucy = Student("Lucy"); // Most IList methods are available: var students = Students().add(james).addAll([sara, lucy]); expect(students, [james, sara, lucy]); // Prints: "Hello James, Sara, Lucy." print(students.greetings()); ``` -------------------------------- ### IMap JSON Serialization and Deserialization Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Demonstrates how to convert a Map to an IMap from JSON and an IMap to JSON. ```dart // --- JSON --- IMap fromJson = IMap.fromJson({'a': 1}, (v) => v as int); Object toJson = m.toJson((v) => v); ``` -------------------------------- ### Create Custom Immutable List-Backed Collection with FromIListMixin Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Use FromIListMixin to compose IList into a strongly-typed immutable class. Provide `iter` for the inner collection and `newInstance` for the copy factory. ```dart import 'package:fast_immutable_collections/fast_immutable_collections.dart'; class Student implements Comparable { final String name; const Student(this.name); @override int compareTo(Student other) => name.compareTo(other.name); @override String toString() => name; @override bool operator ==(Object o) => o is Student && name == o.name; @override int get hashCode => name.hashCode; } // --- Strongly-typed list-backed collection --- class Students with FromIListMixin { final IList _students; Students([Iterable? students]) : _students = IList(students); @override Students newInstance(IList ilist) => Students(ilist); @override IList get iter => _students; String greet() => 'Hello ${_students.join(', ')}.'; } void main() { final james = Student('James'); final sara = Student('Sara'); final lucy = Student('Lucy'); Students students = Students().add(james).addAll([sara, lucy]); print(students.greet()); // Hello James, Sara, Lucy. print(students.length); // 3 // Standard IList operations available via mixin Students sorted = students.sort(); print(sorted.greet()); // Hello James, Lucy, Sara. // Iterate using .iter for (Student s in students.iter) print(s.name); } ``` -------------------------------- ### Construct and Use ListSet Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt ListSet implements List and Set with a fixed size, offering O(1) index access and contains checks. It uses less memory than LinkedHashSet and supports efficient sorting. ```dart import 'package:fast_immutable_collections/fast_immutable_collections.dart'; // --- Construction --- ListSet ls = ListSet.of([3, 1, 2, 1, 3]); // duplicates dropped: [3,1,2] ListSet sorted = ListSet.of([3,1,2], sort: true); // [1,2,3] ListSet empty = ListSet.empty(); // --- Use as List --- print(ls[0]); // 3 print(ls.length); // 3 print(ls.indexOf(2)); // 2 // --- Use as Set --- print(ls.contains(1)); // true l s.remove(1); // ListSet.remove mutates the set view // --- Sort in place --- ListSet toSort = ListSet.of([5, 2, 8, 1]); toSort.sort(); print(toSort.join(',')); // 1,2,5,8 // --- Assignment via List interface --- List asList = ls; Set asSet = ls; // --- JSON --- ListSet fromJson = ListSet.fromJson([1,2,3], (e) => e as int); Object j = ls.toJson((e) => e); ``` -------------------------------- ### Managing Global Settings for Immutable Collections Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Configure global behavior for all immutable collections, including auto-flush, manual flush, safety checks, and pretty printing. Global configurations should be set once at application startup and then locked. ```dart import 'package:fast_immutable_collections/fast_immutable_collections.dart'; // --- Auto-flush (default: on) --- ImmutableCollection.autoFlush = false; // disable IList.flushFactor = 100; // flush after 100 operations (default 500) ISet.flushFactor = 50; IMap.flushFactor = 50; // --- Manual flush (chainable getter) --- IList heavy = [1,2,3].lock.add(4).add(5).add(6); print(heavy.isFlushed); // may be false if under the flushFactor heavy = heavy.flush; // collapse to flat representation print(heavy.isFlushed); // true // --- Disallow unsafe constructors --- ImmutableCollection.disallowUnsafeConstructors = true; // IList.unsafe([1,2,3], config: IList.defaultConfig); // now throws // --- Pretty print --- ImmutableCollection.prettyPrint = true; print([1, 2, 3].lock); // IList[1, 2, 3] // --- Lock config at app startup --- void main() { IList.defaultConfig = const ConfigList(isDeepEquals: true); ISet.defaultConfig = const ConfigSet(sort: false); IMap.defaultConfig = const ConfigMap(sort: false); ImmutableCollection.autoFlush = true; ImmutableCollection.lockConfig(); // Now nothing can change the global config any more. runApp(MyApp()); } ``` -------------------------------- ### Create Const IMap Instances Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Instantiate a const IMap using IMap.empty() or IMapConst. Follow rules for const keyword and explicit assignment to IMap. Sorted maps can only be created if empty. ```dart const IMap imap1 = IMap.empty(); const IMap imap2 = IMapConst({}); const IMap imap3 = IMapConst({'a': 1, 'b':2}); const IMap imap4 = IMapConst({'a': 1, 'b':2}, ConfigMap(isDeepEquals: false)); const IMap imap5 = IMapConst({}, ConfigMap(sort: true)); ``` -------------------------------- ### Mutate IList (Returns New Instance) Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Illustrates common mutation operations on an IList, such as adding, removing, replacing, and sorting elements. Each operation returns a new IList, leaving the original unchanged. ```dart IList list = [1, 2, 3].lock; list = list.add(4); // [1, 2, 3, 4] list = list.addAll([5, 6]); // [1, 2, 3, 4, 5, 6] list = list.remove(1); // removes first occurrence of 1 list = list.removeAll([3, 5]); // removes all occurrences of 3 and 5 list = list.removeMany(2); // removes ALL occurrences of 2 list = list.removeDuplicates(); // keeps only first occurrence of each list = list.removeNulls(); // removes null elements list = list.replace(0, 99); // replace at index → [99, ...] list = list.insert(1, 42); // insert at index list = list.sort(); // returns sorted copy ``` -------------------------------- ### ISet Set Operations Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Shows how to perform standard set operations like union, intersection, and difference between two ISet instances. ```dart ISet s1 = {1, 2, 3}.lock; ISet s2 = {2, 3, 4}.lock; ISet union = s1.union(s2); // {1,2,3,4} ISet intersect = s1.intersection(s2);// {2,3} ISet difference = s1.difference(s2); // {1} ``` -------------------------------- ### Transforming and Converting IList Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates chaining various list operations like sort, map, take, and converting the result to an IList using .toIList(). ```dart IList ilist = ['Bob', 'Alice', 'Dominic', 'Carl'].lock .sort() // Alice, Bob, Carl, Dominic .map((name) => name.length) // 5, 3, 4, 7 .take(3) // 5, 3, 4 .toIList() .sort() // 3, 4, 5 .toggle(4) // 3, 5, .toggle(2); // 3, 5, 2; ``` -------------------------------- ### Create IMap from Iterable with Mappers Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Shows how to create an IMap from an Iterable using key and value mapping functions. Results in {"JIM": 3, "DAVID": 5}. ```dart IMap imap = IMap.fromIterable(["Jim", "David"], keyMapper: (name) => name.toUppercase(), valueMapper: (name) => name.length); ``` -------------------------------- ### Flexible Constructor for IList Fields Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Shows how to design a class constructor to accept any Iterable for an IList field, providing flexibility and efficiency. ```dart class Students { final IList names; Students(Iterable names) : names = IList(names); } ``` -------------------------------- ### Locking Maps to IMap and IMapOfSets Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates how to convert a regular Map to an IMap and a Map of Sets to an IMapOfSets using the .lock property. ```dart /// Map to IMap IMap map = {'a': 1, 'b': 2}.lock; /// Map to IMapOfSets IMapOfSets map = {'a': {1, 2}, 'b': {3, 4}}.lock; ``` -------------------------------- ### IMap Access and Unlocking Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Shows how to access values in an IMap, check for key/value existence, and unlock the IMap into a mutable Map. ```dart // --- Access --- int? val = m['b']; int? val2 = m.get('b'); bool has = m.containsKey('b'); bool hasV = m.containsValue(99); // --- Unlock --- Map mutable = m.unlock; Map sorted = m.unlockSorted; // sorted by key Map view = m.unlockView; Map lazy = m.unlockLazy; ``` -------------------------------- ### Replace Item in IList Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Shows how to use the `replace` method to create a new IList with an item at a specific index changed. ```dart IList ilist = ['Bob', 'Alice', 'Dominic'].lock; // Results in ['Bob', 'John', 'Dominic'] ilist = ilist.replace(1, 'John'); ``` -------------------------------- ### Iterate Through Custom Collection Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Shows how to iterate through the custom Students collection using the .iter method, which is provided by the mixin. ```dart for (Student student in students.iter) { ... } ``` -------------------------------- ### Configure ISet Global Defaults Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates how to change the global default configuration for ISet. The default configuration is ConfigSet(isDeepEquals: true, sort: false, cacheHashCode: true). ```dart defaultConfig = ConfigSet(isDeepEquals: false, sort: true, cacheHashCode: false); ``` -------------------------------- ### Enforcing Custom Configurations for IList Fields Source: https://github.com/marcglasberg/fast_immutable_collections/blob/master/README.md Demonstrates how to enforce custom configurations for an IList field within a class constructor using `IList.withConfig`. ```dart class Students { static const config = ConfigList(isDeepEquals: false); final IList names; Students(Iterable names) : names = IList.withConfig(names, config); } ``` -------------------------------- ### IList Equality Checks Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Explains how to compare IList instances for equality. By default, it performs a deep comparison of elements. `same` checks for instance identity, and `equalItems` checks if elements are equal regardless of order. ```dart IList x = [1, 2, 3].lock; IList y = [1, 2, 3].lock; print(x == y); // true (deep equals by default) print(x.same(y)); // false (different internal instances) print(x.equalItems(y)); // true ``` -------------------------------- ### JSON Serialization for IList Source: https://context7.com/marcglasberg/fast_immutable_collections/llms.txt Shows how to serialize an IList to JSON and deserialize JSON back into an IList, including type casting for elements during deserialization. ```dart IList fromJson = IList.fromJson([1, 2, 3], (e) => e as int); Object json = fromJson.toJson((e) => e); // [1, 2, 3] ```