Home > Back-end >  How to get extract even keys from Map?
How to get extract even keys from Map?

Time:09-27

I would like to extract the even keys from my Map and put them in another sheet/array for further work with them. I wrote a function, but it returns me all the keys of my Map tell me how I can fix it?

void main() {
final  evenNum = [];
final testMap = <int, String>{
    1: 'Text',
    2: 'Text',
    3: 'Text',
    4: 'Text',
    5: 'Text',
    6: 'Text',
  };

 for (var n in testMap.keys){
    if(n / 2 == 0);
     evenNum.add(n);
}
 print(evenNum);
}

CodePudding user response:

The issue on end colonif(n / 2 == 0); and %(modular) instead of /(division)

It will be

if (n % 2 == 0) {
  evenNum.add(n);
}

Or you can use

if (n.isEven) {
  evenNum.add(n);
}

CodePudding user response:

the problem is in the condition in the if statement, you should use mod operator like this:

if (n % 2 == 0){
  evenNum.add(n);
}

CodePudding user response:

Try below code:

void main() {
  final evenNum = [];
  final testMap = <int, String>{
    1: 'Text',
    2: 'Text',
    3: 'Text',
    4: 'Text',
    5: 'Text',
    6: 'Text',
  };

  for (var n in testMap.keys) {
    if (n % 2 == 0) {
      evenNum.add(n);
    }
  }

  print(evenNum);
}

Result: [2, 4, 6]

CodePudding user response:

As user pskink suggested in his comment, you should use .where for the most concise way to get all the even keys. A for loop would also work as others have suggested.

void main() {
  final testMap = <int, String>{
    1: 'Text',
    2: 'Text',
    3: 'Text',
    4: 'Text',
    5: 'Text',
    6: 'Text',
  };

  final evenNums = testMap.keys.where((key) => key.isEven);
  // assert that every number is even -> true
  assert(evenNums.every((number) => number.isEven));
}
  • Related