D
DSA in DartBeginner10 XP3 min read

What are the main collection types in Dart and when do you use each?

TL;DR: List: ordered, indexed, allows duplicates (O(1) access by index). Set: unordered, unique elements (O(1) lookup). Map: key-value pairs (O(1) lookup by key). Queue: efficient add/remove from both ends.

Full Answer

AspectCollectionCharacteristics
List<T>Ordered, duplicates, index accessO(1) get, O(n) search, O(1) add to end
Set<T>Unordered, unique elements (HashSet)O(1) contains, add, remove
Map<K,V>Key-value pairs, unique keys (HashMap)O(1) lookup, add, remove by key
Queue<T>Ordered, efficient both-end opsO(1) addFirst, addLast, removeFirst
๐ŸŽฏ

Use Set for checking membership (contains) โ€” it's O(1) vs List's O(n). If you check 'is this ID in the list' frequently, convert to a Set.

Code Examples

dartChoosing the right collection
Output
// Set.contains: O(1) vs List.contains: O(n)
// Map lookup: O(1) vs searching List of objects: O(n)

Common Mistakes

  • โœ—Using List.contains() in a hot path when Set.contains() is O(1)
  • โœ—Using Map.values.toList() when you just need to iterate โ€” .values already is iterable

Interview Tip

๐Ÿ’ก

Show you know the time complexities. The most impactful optimization is often replacing a List.contains() in a loop (O(nยฒ)) with a Set.contains() (O(n)).

#list#set#map#queue#collections