sortTo method

List<T> sortTo([
  1. int compare(
    1. T a,
    2. T b
    )?
])

Sorts this list according to the order specified by the compare function.

The compare function must act as a Comparator.

compare 関数で指定された順序に従って、このリストを並べ替えます。

compare 関数は Comparator として機能する必要があります。

final numbers = <String>['two', 'three', 'four'];
// Sort from shortest to longest.
final sorted = numbers.sortTo((a, b) => a.length.compareTo(b.length));
print(sorted); // [two, four, three]

The default List implementations use Comparable.compare if compare is omitted.

compare が省略されている場合、デフォルトの List 実装は Comparable.compare を使用します。

final numbers = <int>[13, 2, -11, 0];
final sorted = numbers.sortTo();
print(sorted); // [-11, 0, 2, 13]

In that case, the elements of the list must be Comparable to each other.

A Comparator may compare objects as equal (return zero), even if they are distinct objects.

The sortTo function is not guaranteed to be stable, so distinct objects that compare as equal may occur in any order in the result:

その場合、リストの要素は互いに Comparable でなければなりません。

Comparator は、それらが異なるオブジェクトであっても、オブジェクトを等しいものとして比較する (0 を返す) 場合があります。

sortTo関数は安定していることが保証されていないため、比較すると等しいと見なされる個別のオブジェクトが、結果内で任意の順序で発生する可能性があります。

final numbers = <String>['one', 'two', 'three', 'four'];
final sorted numbers.sortTo((a, b) => a.length.compareTo(b.length));
print(sorted); // [one, two, four, three] OR [two, one, four, three]

Implementation

List<T> sortTo([int Function(T a, T b)? compare]) {
  final sorted = List<T>.from(this);
  sorted.sort(compare);
  return sorted;
}