How to count items' occurence in a List

后端 未结 1 1681
逝去的感伤
逝去的感伤 2020-12-03 23:47

I am new to Dart. Currently I have a List of duplicate items, and I would like to count the occurence of them and store it in a Map.

var elements = [\"a\",          


        
相关标签:
1条回答
  • 2020-12-04 00:05

    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!

    0 讨论(0)
提交回复
热议问题