Sub topic 9
Sorting and Searching Dart Collections
Assume you know Dart variables, functions, generics, and null safety. This chapter focuses on finding values and ordering lists. Sorting changes a list, so understanding mutability is important.
Sorting a list
List.sort orders the elements in place. The method changes the original list and returns void. With numbers, Dart can use their natural order. For other types, provide a comparison function.
A comparison function receives two elements:
- Return a negative number when the first element comes before the second.
- Return zero when they have the same order.
- Return a positive number when the first element comes after the second.
class Product {
final String name;
final double price;
Product(this.name, this.price);
}
void main() {
final scores = [5, 3, 8, 1, 9, 2];
scores.sort();
print(scores); // [1, 2, 3, 5, 8, 9]
scores.sort((a, b) => b.compareTo(a));
print(scores); // [9, 8, 5, 3, 2, 1]
final products = [
Product('Book', 12.0),
Product('Pen', 2.5),
Product('Bag', 25.0),
];
products.sort((a, b) => a.price.compareTo(b.price));
print(products.map((product) => product.name).toList());
// [Pen, Book, Bag]
}To preserve the original list, make a shallow copy before sorting. A shallow copy contains the same element objects, but the list itself is different.
final original = [5, 3, 8];
final sorted = [...original]..sort();
print(original); // [5, 3, 8]
print(sorted); // [3, 5, 8]| Task | Expression | Result |
|---|---|---|
| Ascending numbers | `values.sort()` | Smallest first |
| Descending numbers | `values.sort((a, b) => b.compareTo(a))` | Largest first |
| Sort a copy | `[...values]..sort()` | Original remains unchanged |
Searching a collection
Lists provide several search methods. These methods usually scan from the beginning, so they are linear searches.
contains(value)checks whether an equal value exists.indexOf(value)returns the first matching index, or-1.indexWhere(test)returns the first index that satisfies a condition, or-1.firstWhere(test)returns the first matching element. UseorElsewhen no match is possible.any(test)checks whether at least one element matches.every(test)checks whether all elements match.
void main() {
final temperatures = [18, 24, 31, 27];
print(temperatures.contains(24)); // true
print(temperatures.indexOf(31)); // 2
print(temperatures.indexWhere((value) => value > 28)); // 2
print(temperatures.any((value) => value < 0)); // false
print(temperatures.every((value) => value >= 18)); // true
final cool = temperatures.firstWhere(
(value) => value < 20,
orElse: () => -1,
);
print(cool); // 18
}For membership checks, a Set is usually a better choice than repeatedly searching a list. A Map provides direct lookup by key. containsValue searches map values and may scan the whole map.
final allowedIds = {10, 20, 30};
print(allowedIds.contains(20)); // true
final names = {10: 'Ada', 20: 'Lin'};
print(names.containsKey(20)); // true
print(names[20]); // LinExercise
How can you sort [4, 1, 3] in descending order without changing the original list?
Show answer
Create a copy and sort it with a reversed comparator: final result = [...values]..sort((a, b) => b.compareTo(a));.