List, Set, Map Overview
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 63 of 110.
Dart provides three core collection types that you'll use constantly when building applications. Each serves a different purpose for organizing and accessing data.
A List is an ordered collection where elements are accessed by index. Items maintain their insertion order and duplicates are allowed:
var fruits = ['apple', 'banana', 'apple'];
print(fruits[0]); // apple
print(fruits.length); // 3A Set is an unordered collection of unique elements. If you try to add a duplicate, it's simply ignored:
var uniqueNumbers = {1, 2, 3, 2, 1};
print(uniqueNumbers); // {1, 2, 3}A Map stores key-value pairs, letting you look up values by their associated key:
var ages = {'Alice': 30, 'Bob': 25};
print(ages['Alice']); // 30Here's a quick comparison:
| Collection | Ordered | Duplicates | Access By |
|---|---|---|---|
| List | Yes | Allowed | Index |
| Set | No | Not allowed | Contains check |
| Map | No* | Unique keys | Key |
These collections become even more powerful when combined with generics, which you'll explore in the upcoming lessons to create type-safe collections that work with your custom classes.
Challenge
EasyLet's build a classroom management system that uses all three collection types to organize student data in different ways. You'll see how Lists, Sets, and Maps each serve distinct purposes when managing the same information.
You'll organize your code into two files:
classroom.dart: Create aClassroomclass that manages student data using all three collection types:- A
List<String>calledattendanceOrderto track students in the order they arrived (duplicates allowed if a student signs in multiple times) - A
Set<String>calleduniqueStudentsto track which students are present (no duplicates) - A
Map<String, int>calledscoresto store each student's test score
recordArrival(String name)- adds the name to both the attendance list and the unique students setsetScore(String name, int score)- stores the student's score in the mapprintReport()- prints the classroom report (format shown below)
- A
main.dart: Import your classroom file and demonstrate the system:- Create a
Classroominstance - Record arrivals in this order:
'Alice','Bob','Alice','Carol','Bob' - Set scores: Alice =
95, Bob =87, Carol =92 - Call
printReport()
- Create a
The printReport() method should output:
Arrival Order: [Alice, Bob, Alice, Carol, Bob]
Unique Students: {Alice, Bob, Carol}
Scores: {Alice: 95, Bob: 87, Carol: 92}Notice how the List preserves every arrival (including duplicates), the Set automatically keeps only unique names, and the Map associates each student with their score. Each collection type serves its purpose perfectly!
Expected output:
Arrival Order: [Alice, Bob, Alice, Carol, Bob]
Unique Students: {Alice, Bob, Carol}
Scores: {Alice: 95, Bob: 87, Carol: 92}Cheat sheet
Dart provides three core collection types for organizing data:
List - An ordered collection where elements are accessed by index. Duplicates are allowed:
var fruits = ['apple', 'banana', 'apple'];
print(fruits[0]); // apple
print(fruits.length); // 3Set - An unordered collection of unique elements. Duplicates are automatically ignored:
var uniqueNumbers = {1, 2, 3, 2, 1};
print(uniqueNumbers); // {1, 2, 3}Map - Stores key-value pairs for lookup by key:
var ages = {'Alice': 30, 'Bob': 25};
print(ages['Alice']); // 30| Collection | Ordered | Duplicates | Access By |
|---|---|---|---|
| List | Yes | Allowed | Index |
| Set | No | Not allowed | Contains check |
| Map | No* | Unique keys | Key |
Try it yourself
import 'classroom.dart';
void main() {
// TODO: Create a Classroom instance
// TODO: Record arrivals in this order: 'Alice', 'Bob', 'Alice', 'Carol', 'Bob'
// TODO: Set scores: Alice = 95, Bob = 87, Carol = 92
// TODO: Call printReport() to display the classroom data
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor