This tutorial shows you how to count the frequency of elements in a List
using Dart.
List
is a data type that stores a collection of elements. Unlike Set
, a List
allows you to store duplicate elements. In other words, an element can appear multiple times in a List
. If you need to find out how many times a value is in a List
using Dart programming language, below are the examples.
This tutorial uses the below List
for example.
final values = ['a', 'b', 'a', 'c', 'd', 'b', 'e', 'd', 'a', 'c', 'b'];
Using Loop
The most basic way to count the frequency of an element is by iterating over the List
. Create a variable as a counter and increment the counter if the current element matches the one to be counted.
int countOccurrencesUsingLoop(List<String> values, String element) {
if (values.isEmpty) {
return 0;
}
int count = 0;
for (String value in values) {
if (value == element) {
count++;
}
}
return count;
}
countOccurrencesUsingLoop(values, 'a');
// Output: 3
Using Iterable.where
Dart's List
is a sub-type of Iterable
and therefore it can use Iterable
's methods. For this purpose, the most suitable method to use is where
. It returns a new Iterable
with all elements that satisfy the function passed as a predicate.
The passed function will be applied to each element. It accepts a parameter which is the element value and returns a bool
value. An element is included in the new List
if the function returns true
. In this case, the function should return true
only if the passed value matches the element to be counted. Then, access the length
property to get the number of occurrences. The code is much shorter than the previous example.
int countOccurrencesUsingWhere(List<String> values, String element) {
return values.where((e) => e == element).length;
}
Example:
countOccurrencesUsingWhere(values, 'a');
// Output: 3
Count the Occurrences of Each Element
If you have a List
that's rarely modified and the system needs to get the frequency of any element many times, it's better to store the frequency of each element in a Map
. The Map
's keys are the elements, while the values are the occurrences of the respective element. Therefore, you only need one iteration to build the counter. Then, you can get the occurrence of any element from the Map
.
Map<String, int> countAllOccurrences(List<String> values) {
final counter = <String, int>{};
for (final value in values) {
counter.update(value, (count) => count + 1, ifAbsent: () => 1);
}
return counter;
}
Example:
Map<String, int> counter = countAllOccurrences(values);
// Output: {a: 3, b: 3, c: 2, d: 2, e: 1}
counter['a']; // 3
Summary
There are several ways to count the occurrences of elements in a List
using Dart. The most basic way is using a loop. Another alternative with much shorter code is using the where
method of Iterable
. If there is a requirement to get the frequency of elements over and over, the recommended way is to create a counter using a Map
.