distinctBy<K> method

  1. @useResult
KtList<T> distinctBy<K>(
  1. K selector(
    1. T
    )
)

Returns a list containing only elements from the given collection having distinct keys returned by the given selector function.

The elements in the resulting list are in the same order as they were in the source collection.

Implementation

@useResult
KtList<T> distinctBy<K>(K Function(T) selector) {
  final set = hashSetOf<K>();
  final list = mutableListOf<T>();
  for (final element in iter) {
    final key = selector(element);
    if (set.add(key)) {
      list.add(element);
    }
  }
  return list;
}