Async and Practical
Word Count with Map
Counting words is a classic map exercise: split the text, walk each word, and increment its tally in a map. Default Dart maps keep insertion order, so the summary stays stable.
Program
Play the program to tally six words and build a deterministic summary string.
word_count.dart
Replay: real traced execution (multi-file project)
void main() {
var text = 'red blue red green blue red';
var words = text.split(' ');
var counts = <String, int>{};
for (var w in words) {
counts[w] = (counts[w] ?? 0) + 1;
}
var entries = counts.entries;
var parts = entries.map((e) => '${e.key}:${e.value}');
var summary = parts.join(',');
print(summary);
}
text ← red blue red green blue red
1void main() {2 var text = 'red blue red green blue red';3 var words = text.split(' ');values this stepred blue red green blue redtextwords ← [red, blue, red, green, blue, red]
2var text = 'red blue red green blue red';3var words = text.split(' ');4var counts = <String, int>{};values this step[red, blue, red, green, blue, red]wordscounts ← {}
3var words = text.split(' ');4var counts = <String, int>{};5for (var w in words) {values this step{}countscounts ← {red: 3, blue: 2, green: 1}
4var counts = <String, int>{};5for (var w in words) {6 counts[w] = (counts[w] ?? 0) + 1;values this step{red: 3, blue: 2, green: 1}counts6 wordsloopentries ← red, blue, green
7}8var entries = counts.entries;9var parts = entries.map((e) => '${e.key}:${e.value}');values this stepred, blue, greenentriesparts ← [red:3, blue:2, green:1]
8var entries = counts.entries;9var parts = entries.map((e) => '${e.key}:${e.value}');10var summary = parts.join(',');values this step[red:3, blue:2, green:1]partssummary ← red:3,blue:2,green:1
9var parts = entries.map((e) => '${e.key}:${e.value}');10var summary = parts.join(',');11print(summary);values this stepred:3,blue:2,green:1summaryprint(summary);
10 var summary = parts.join(',');11 print(summary);12}outputred:3,blue:2,green:1values this stepred:3,blue:2,green:1summary
split
`'red blue ... red'.split(' ')` returns `[red, blue, red, green, blue, red]`.
counter map
`?? 0` starts unseen words at zero before the program adds one.
insertion order
Walking `counts.entries` keeps insertion order, so the joined summary is deterministic.