Flutter & Dart: Count Occurrences of each Element in a List

When working with Dart and Flutter, there might be cases where you want to count the occurrences of each element in a given list. The simple example below will demonstrate how to do that:
void main() {
// this list contains both strings and numbers
final List myList = [
'blue',
'red',
'amber',
'blue',
'green',
'orange',
'red',
'blue',
'pink',
'amber',
'blue',
123,
123,
234
];
// this map has keys and values that are the elements and their occurrences in the list, respectively
final Map counts = {};
// loop through the list
// If an element appears for the first time, set it to a key of the map and the corresponding value to 1
// If an element is already used to a key, its corresponding value is incremented by 1
myList.map((e) => counts.containsKey(e) ? counts[e]++ : counts[e] = 1);
// print out the result
print(counts);
}
Output:
{
blue: 4,
red: 2,
amber: 2,
green: 1,
orange: 1,
pink: 1,
123: 2,
234: 1
}
That’s it. Further reading:
- Dart: Extract a substring from a given string (advanced)
- Dart: Convert Class Instances (Objects) to Maps and Vice Versa
- How to implement a loading dialog in Flutter
- Environment Variables in Flutter: Development & Production
- Flutter & Hive Database: CRUD Example
- Dart & Flutter: Get the Index of a Specific Element in a List
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.
Subscribe
0 Comments