Comparator<T> constructor
const
Comparator<T> ()
An abstract class that imposes a total ordering on a collection of objects of type T
.
A Comparator
can be used to:
- Sort lists (
List.sort(comparator)
). - Control ordering in sorted collections (e.g., custom trees or ordered maps).
- Provide alternate sort logic for types that don’t implement
Comparable
.
This Dart class is inspired by Java's java.util.Comparator
.
📌 Example Usage
final Comparator<String> byLength = Comparator.comparing((s) => s.length);
final names = ['Alice', 'Bob', 'Christina'];
names.sort(byLength.compare);
print(names); // [Bob, Alice, Christina]
You can also chain comparators:
final byLengthThenAlphabet = Comparator.comparing((s) => s.length)
.thenComparing(Comparator.naturalOrder());
final list = ['Tom', 'Ann', 'Tim', 'Jim', 'Alex'];
list.sort(byLengthThenAlphabet.compare);
print(list); // [Ann, Jim, Tom, Tim, Alex]
Implementation
const Comparator();