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

Last updated on March 16, 2022 Pennywise Loading... 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 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:

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

You May Also Like