To find the element with the maximum number of occurrences in a list in Dart, you can use a Map to count the occurrences.
In this example,
data
with several integer elements.Map
to count the occurrences of each element.void main() {
List<int> data = [1, 2, 2, 3, 3, 3, 4];
Map<int, int> count = {};
for (var num in data) {
if (count.containsKey(num)) {
count[num] = count[num]! + 1;
} else {
count[num] = 1;
}
}
int mostCommon = data[0];
int maxCount = 0;
count.forEach((key, value) {
if (value > maxCount) {
maxCount = value;
mostCommon = key;
}
});
print('Element with the maximum occurrences is: $mostCommon');
}
Element with the maximum occurrences is: 3
In this example,
words
with several string elements.Map
to count the occurrences of each element.void main() {
List<String> words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
Map<String, int> count = {};
for (var word in words) {
if (count.containsKey(word)) {
count[word] = count[word]! + 1;
} else {
count[word] = 1;
}
}
String mostCommon = words[0];
int maxCount = 0;
count.forEach((key, value) {
if (value > maxCount) {
maxCount = value;
mostCommon = key;
}
});
print('Element with the maximum occurrences is: $mostCommon');
}
Element with the maximum occurrences is: apple
In this tutorial, we learned How to find the Element with Maximum Number of Occurrences in a List in Dart language with well detailed examples.