I have list type of String with elements (Example: ['Hello', 'World', 'one', 'two']).
I need to run this list and find the numbers in it.
My solution:
class DetectNumber {
final collection = <String>['Hello', 'nine', 'world', 'one', 'two'];
final resNumbList = <int>[];
void res() {
for (int i = 0; i < collection.length; i ) {
if (collection[i] == 'zero') {
resNumbList.add(0);
} else if (collection[i] == 'one') {
resNumbList.add(1);
} else if (collection[i] == 'two') {
resNumbList.add(2);
} else if (collection[i] == 'three') {
resNumbList.add(3);
} else if (collection[i] == 'four') {
resNumbList.add(4);
} else if (collection[i] == 'five') {
resNumbList.add(5);
} else if (collection[i] == 'six') {
resNumbList.add(6);
} else if (collection[i] == 'seven') {
resNumbList.add(7);
} else if (collection[i] == 'eight') {
resNumbList.add(8);
} else if (collection[i] == 'nine') {
resNumbList.add(9);
}
}
print(resNumbList); // Output: [9, 1, 2]
}
}
Is there a shorter way to solve this task?
I have an idea of a solution via Map.
I have an idea of a solution via Map. Put String type keys and int type values in the Map
(Example: {'one': 1, 'two' : 2, ..., 'nine' : 9}
).
Then compare the List with this Map. Please help me implement this.
CodePudding user response:
Like
const digits = {'one': 1, 'two' : 2, /*...*/ 'nine' : 9};
final resNumbList = collection.where(digits.containsKey).map((e) => digits[e]);
This filters the collection for strings contained in the map and then translates these strings using the map.