sort method

void sort([
  1. Comparator<T>? comparator
])

Sorts the set in place.

  • Works with LinkedHashSet, the default implementation of Set.
  • Sorting is nonsensical for instances of HashSet since the iteration order is not specified.

Implementation

void sort([Comparator<T>? comparator]) {
  if (isEmpty) return;
  final tmp = List<T>.of(this);
  if (comparator != null) {
    tmp.sort(comparator);
  } else if (first is Comparable) {
    tmp.sort(); // Sort using default comparator.
  } else {
    throw ErrorOfType<SortingNotSupported<T>>(
        message: 'Error trying to sort the set: $this.',
        invalidState: 'Type \'$T\' is not comparable.',
        expectedState: 'Try specifying a valid comparator for type \'$T\'.');
  }
  clear();
  addAll(tmp);
}