distinct method

  1. @lazy
  2. @useResult
Iterable<E> distinct({
  1. required Select<E, Object?> by,
})

Returns a lazy iterable with only distinct elements.

Two elements are distinct if the values returned by by are not equal according to ==. Earlier elements are replaced by later elements if their values are equal.

This function is non-deterministic when this iterable is unordered, i.e. HashSet.

See toSet for creating a distinct Iterable by comparing elements.

final set = {('a', 1), ('b', 1), ('c', 2)};
final unordered = set.distinct(by: (e) => e.$2);

print(unordered); // [('a', 1), ('c', 2)] or [('b', 1), ('c', 2)]

Implementation

@lazy @useResult Iterable<E> distinct({required Select<E, Object?> by}) sync* {
  final existing = <Object?>{};
  for (final element in this) {
    if (existing.add(by(element))) {
      yield element;
    }
  }
}