示例工程 ch03-types-collections
ch03-types-collections/lib/collections.dart
/// 集合:`List` / `Set` / `Map` 与它们的惯用法。
///
/// 关键差异(Go 程序员最容易忽略的一条):
/// **Dart 的 Map / Set 默认保持插入顺序**(LinkedHashMap / LinkedHashSet),
/// 而 Go 的 map 遍历顺序是随机的,C 里更没有"有序字典"这回事。
library;
/// `map` / `where` / `fold` 是链式的高阶函数,比手写循环短,但注意每步都会新建集合。
List<int> squaresOfEven(List<int> xs) =>
xs.where((int x) => x.isEven).map((int x) => x * x).toList();
/// 分组:`Map<K, List<V>>` 是 Dart 里的标准做法(Go 里是 `map[K][]V`)。
Map<int, List<String>> groupByLength(List<String> words) {
final result = <int, List<String>>{};
for (final w in words) {
// `putIfAbsent` / `??=` 都能避免手写"先判断 key 是否存在"。
(result[w.length] ??= <String>[]).add(w);
}
return result;
}
/// 词频统计:`??=` 是 null-aware assignment,等价于 `if (m[k] == null) m[k] = 0`。
Map<String, int> wordCounts(String text) {
final counts = <String, int>{};
for (final raw in text.toLowerCase().split(RegExp(r'\s+'))) {
final word = raw.replaceAll(RegExp(r'[^a-z0-9]'), '');
if (word.isEmpty) continue;
counts[word] = (counts[word] ?? 0) + 1;
}
return counts;
}
/// `Set` 去重;Dart 的 Set 用 `hashCode` + `==` 判重,与 C++ 的 unordered_set 同理。
Set<String> uniqueWords(String text) =>
text.toLowerCase().split(RegExp(r'[^a-z]+')).where((String w) => w.isNotEmpty).toSet();
/// 排序:`sort` 是**原地**修改(像 Go 的 `sort.Ints`),
/// 所以要保留原序必须先 `[...]` 复制(Go 里是 `slices.Clone`)。
List<int> sortedDescending(List<int> xs) => [...xs]..sort((int a, int b) => b.compareTo(a));
/// 固定长度列表:初始化后不能增删,但能改元素——像 C 的 `int arr[3]`。
List<int> fixedSlots() => List<int>.filled(3, 0);
/// 生成序列:等价 Go 的 `for i := 0; i < n; i++ { append(...) }`。
List<int> range(int n) => List<int>.generate(n, (int i) => i);
/// 不可变视图:对它的任何写操作抛 `UnsupportedError`(C 的 `const` 数组 / Go 没有对应物)。
List<String> readOnlyTags() => List<String>.unmodifiable(<String>['dart', 'flutter']);
/// 集合推导(collection-for / collection-if / spread):Dart 独有的紧凑写法。
List<String> buildTags({
bool starred = false,
List<String> extra = const <String>[],
List<String>? more,
}) =>
[
'dart',
if (starred) 'starred', // collection-if
for (final e in extra) 'extra:$e', // collection-for
...?more, // spread 可空集合:...? 遇到 null 直接跳过
];
/// 嵌套集合:`Map<String, Map<String, int>>` 在配置文件里很常见。
Map<String, Map<String, int>> inventory() => {
'fruits': {'apple': 3, 'pear': 5},
'tools': {'hammer': 1},
};