distinctBy method
Creates a new List containing distinct elements based on the result of the given predicate.
The function takes a predicate parameter, which represents a function that generates a unique key
for each element in the Iterable. It creates a HashSet to keep track of the unique keys encountered.
It then iterates over each element in the Iterable and checks if the key generated by the predicate
has not been encountered before. If it hasn't, the element is added to the result List.
Returns a new List containing distinct elements based on the result of the predicate.
Example:
List<String> names = ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob'];
List<String> distinctNames = names.distinctBy((name) => name);
print(distinctNames); // Output: [Alice, Bob, Charlie]
Implementation
List<T> distinctBy(predicate(T selector)) {
final set = HashSet();
final list = [];
toList().forEach((e) {
final key = predicate(e);
if (set.add(key)) {
list.add(e);
}
});
return List<T>.from(list);
}