flutter 我想反转Map的键和值

ekqde3dh  于 2022-12-27  发布在  Flutter
关注(0)|答案(2)|浏览(128)

如何反转Map的键和值?
例如,{1:a , 2:b , 3:c} => {a:1 ,b:2 ,c:3}

tzdcorbm

tzdcorbm1#

试试下面这段代码:

Map<int, String> map = {1: "a", 2: "b", 3: "c"};

  Iterable<String> values = map.values;
  Iterable<int> keys = map.keys;
  Map<String, int> reversedMap = Map.fromIterables(values, keys);

  print(reversedMap); // {a:1 ,b:2 ,c:3}
jljoyd4f

jljoyd4f2#

您可以执行以下操作:

const items = {1:'a' , 2:'b' , 3:'c'};

void main() {
  final inverted = items.map((key, value) => MapEntry(value, key));
  print(inverted);
}

它记录

{a: 1, b: 2, c: 3}

相关问题