Home > database >  Is it possible to convert Iterable with MapEntry type to Map type without looping?
Is it possible to convert Iterable with MapEntry type to Map type without looping?

Time:08-24

A newbie to Dart, who's trying to get into Flutter. Is it possible to convert MapEntry to Map without looping, or shorter method/ better performance way to achieve the same result?

I have a returned type of Iterable, with MapEntry<String, int> like below.

final Map<String, int> laptopPricing = <String, int>{
  'MacM1': 120000,
  'RogFlowX13': 170000,
  'LenovoLegion': 110000
};

const int budgetOnHand = 150000;
final laptopWithinBudget = laptopPricing.entries.where((element) => element.value <= budgetOnHand); //filtering a map using entries's value

print(laptopWithinBudget); //prints (MapEntry(MacM1: 120000), MapEntry(LenovoLegion: 110000)) because the "where" method returns an Iterable MapEntry

What I would like to do, is to convert the Iterable with MapEntry, to a simple Map, with just Key and Value, without the "MapEntry" within the collection, and without using any sort of looping method for the conversion. (Just trying to learn and see if it is possible to achieve without using any loop, due to the concern of performance issue) (Also, any best practice/ much better way to do it or advice such as "You shouldn't even use this if you're doing that", is more than welcome :D)

I have managed to achieve it with the map method (as far as I know, this is considered as looping, as it iterate through all the elements within a collection, but please correct me if I'm wrong on that)

final returnsMapUsingLooping = Map.fromIterables(
    laptopWithinBudget.map((e) => e.key),
    laptopWithinBudget.map((e) => e.value));

print(returnsMapUsingLooping); //prints {MacM1: 120000, LenovoLegion: 110000}

Appreciate all the help here, thank you so much.

CodePudding user response:

I have two way for this solution, try it:

final Map<String, int> laptopPricing = <String, int>{'MacM1': 120000, 'RogFlowX13': 170000, 'LenovoLegion': 110000};
final Map<String, int> laptopWithinBudget = <String, int>{};

const int budgetOnHand = 150000;
//first way
for (var element in laptopPricing.entries) {
  if (element.value <= budgetOnHand) {
    laptopWithinBudget.addAll({element.key: element.value});
  }
}
//second way (recommend)
laptopWithinBudget.addEntries(laptopPricing.entries.where((element) => element.value <= budgetOnHand));
print(laptopWithinBudget);

CodePudding user response:

The Map class has a fromEntries named constructor which is exactly what you want here:

final asMap = Map<String, int>.fromEntries(laptopWithinBudget);
print(asMap);

Which yields {MacM1: 120000, LenovoLegion: 110000}.

  • Related