是否可以在不循环的情况下将 MapEntry 类型的 Iterable 转换为 Map 类型?

1 performance dictionary loops iterable flutter

Dart 新手,正在尝试进入 Flutter。是否可以在不循环的情况下将 MapEntry 转换为 Map,或者使用更短的方法/更好的性能方式来实现相同的结果?

我有一个 Iterable 的返回类型,MapEntry<String, int> 如下所示。

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
Run Code Online (Sandbox Code Playgroud)

我想做的是将带有 MapEntry 的 Iterable 转换为一个简单的 Map,只有 Key 和 Value,集合中没有“MapEntry”,并且不使用任何类型的循环方法进行转换。(出于性能问题的考虑,只是尝试学习并看看是否可以在不使用任何循环的情况下实现)(此外,任何最佳实践/更好的方法或建议,例如“您甚至不应该使用如果你这样做的话,这是非常受欢迎的:D)

我已经设法用 map 方法实现了它(据我所知,这被认为是循环,因为它迭代集合中的所有元素,但如果我错了,请纠正我)

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

print(returnsMapUsingLooping); //prints {MacM1: 120000, LenovoLegion: 110000}
Run Code Online (Sandbox Code Playgroud)

感谢这里所有的帮助,非常感谢。

Tom*_*iel 8

该类Map有一个fromEntries命名构造函数,这正是您想要的:

final asMap = Map<String, int>.fromEntries(laptopWithinBudget);
print(asMap);
Run Code Online (Sandbox Code Playgroud)

从而产生{MacM1: 120000, LenovoLegion: 110000}.