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

Updated: March 31, 2023 By: Pennywise Post a comment

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 best strategy to get the job done is to use a map to store the frequency of each element in the list (use the list elements as keys and their counts as values). The next step is to loop over the list and update the map accordingly.

The simple example below will demonstrate how to do that in practice:

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:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles