Reputation: 213
Let's say I have a list of string.
I saw the code on: How to count items' occurence in a List
I want to print the most frequent string as a text in my widget. How do i run this and print it in there?
Do i go by 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;
}
Attached are some screenshots when I return the results
Upvotes: 0
Views: 370
Reputation: 1214
Here you can first create the map of your counted values and then using that map you can get the maximum value of the key.
Source 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 Here
Upvotes: 2