Comparator<T> class
abstract
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]
- Implementers
- Annotations
-
- @Generic(Comparator)
Constructors
- Comparator()
-
An abstract class that imposes a total ordering on a collection of objects of type
T
.const
Properties
- hashCode β int
-
The hash code for this object.
no setterinherited
- runtimeType β Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
compare(
T a, T b) β int -
Compares two values of type
T
for order. -
noSuchMethod(
Invocation invocation) β dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
reversed(
) β Comparator< T> - Returns a comparator that imposes the reverse ordering of this comparator.
-
thenComparing(
Comparator< T> other) β Comparator<T> - Chains another comparator to be used if this comparator returns 0 (equality).
-
thenComparingComparable<
U extends Comparable< (U> >U keyExtractor(T)) β Comparator< T> -
Chains a comparator by extracting a
Comparable
key from each element. -
thenComparingWith<
U> (U keyExtractor(T), Comparator< U> keyComparator) β Comparator<T> -
Chains a comparator by extracting a key with
keyExtractor
and comparing it using the givenkeyComparator
. -
toString(
) β String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) β bool -
The equality operator.
inherited
Static Methods
-
comparing<
T, U extends Comparable< (U> >U keyExtractor(T)) β Comparator< T> -
Creates a comparator based on a
Comparable
key extracted from each element. -
comparingWith<
T, U> (U keyExtractor(T), Comparator< U> keyComparator) β Comparator<T> - Creates a comparator based on a key extractor and a custom comparator for the key.
-
naturalOrder<
T> () β Comparator< T> -
Creates a comparator that compares
Comparable
objects in natural ascending order. -
reverseOrder<
T> () β Comparator< T> -
Creates a comparator that compares
Comparable
objects in reverse (descending) order.