How to count items’ occurence in a List

Play around with this:

  var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
  var map = Map();

  elements.forEach((element) {
    if(!map.containsKey(element)) {
      map[element] = 1;
    } else {
      map[element] += 1;
    }
  });

  print(map);

What this does is:

  • loops through list elements
  • if your map does not have list element set as a key, then creates that element with a value of 1
  • else, if element already exists, then adds 1 to the existing key value

Or if you like syntactic sugar and one liners try this one:

  var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
  var map = Map();

  elements.forEach((x) => map[x] = !map.containsKey(x) ? (1) : (map[x] + 1));

  print(map);

There are many ways to achieve this in all programming languages!

Leave a Comment