打印文本中出现频率最高的值

时间:2021-05-29 14:07:58

标签: list flutter dart

假设我有一个字符串列表。

我在以下位置看到了代码:How to count items' occurence in a List

我想将最常用的字符串作为文本打印在我的小部件中。我如何运行它并将其打印在那里?

我会通过 void main() 吗?

class user with ChangeNotifier {
  static String topWord;

  notifyListeners();
}

void countWord() {
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
  var popular = Map();

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

  print(popular);
return user.topWord = popular; 
}

附上一些返回结果时的截图

Error 1

Error 2

1 个答案:

答案 0 :(得分:1)

在这里您可以首先创建计数值的映射,然后使用该映射可以获得键的最大值。

来源Here

class HomePage extends StatelessWidget {
  String email;
  var maxocc = maxOccurance();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("App Bar"),
      ),
      body: Center(
        child: Container(
          child: Text(maxocc),
        ),
      ),
    );
  }
}

String maxOccurance() {
  var elements = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "a",
    "b",
    "c",
    "f",
    "g",
    "h",
    "h",
    "h",
    "e"
  ];

  // Here creating map of all values and counting it
  final folded = elements.fold({}, (acc, curr) {
    acc[curr] = (acc[curr] ?? 0) + 1;
    return acc;
  }) as Map<dynamic, dynamic>;
  print(folded);

  // Here getting maximum value inside map
  final sortedKeys = folded.keys.toList()
    ..sort((a, b) => folded[b].compareTo(folded[a]));

  return "${sortedKeys.first} occurs maximun times i.e. ${folded[sortedKeys.first]}";
}

这里输出

output

相关问题