How to get Map keys by values in Dart?

ぐ巨炮叔叔 提交于 2020-06-24 11:10:10

问题


In Dart language how to get MAP keys by values?

I have a Map like;

{
  "01": "USD",
  "17": "GBP",
  "33": "EUR"
}

And I need to use values to get keys. How do I do that?


回答1:


var usdKey = curr.keys.firstWhere(
    (k) => curr[k] == 'USD', orElse: () => null);



回答2:


If you will be doing this more than a few times on the same data, you should create an inverse map so that you can perform simple key lookup instead of repeated linear searches. Here's an example of reversing a map (there may be easier ways to do this):

main() {
  var orig = {"01": "USD", "17": "GBP", "33": "EUR"};
  var reversed = Map.fromEntries(orig.entries.map((e) => MapEntry(e.value, e.key)));
  for (var kv in reversed.entries) {
    print(kv);
  }
}

Edit: yes, reversing a map can simply be:

var reversed = orig.map((k, v) => MapEntry(v, k));

Tip of the hat to Joe Conway on gitter. Thanks.




回答3:


You can do the following :

var mapper = { 
              '01' : 'USD',
               '17' : 'GBP'     } 

for(var val in mapper.keys){

  switch(mapper[val]){

        case 'USD' : {
                             print('key for ${mapper[val]} is : ' '${val}');  
            }

          break;

        case 'GBP' : {
                             print('key for ${mapper[val]} is : ' '${val}');   
               } 

        }
          }



回答4:


There is another one method (similar to Günter Zöchbauer answer):

void main() {

  Map currencies = {
     "01": "USD",
     "17": "GBP",
     "33": "EUR"
  };

  MapEntry entry = currencies.entries.firstWhere((element) => element.value=='GBP', orElse: () => null);

  if(entry != null){
    print('key = ${entry.key}');
    print('value = ${entry.value}');
  }

}

In this code, you get MapEntry, which contains key and value, instead only key in a separate variable. It can be useful in some code.




回答5:


Map map = {1: 'one', 2: 'two', 3: 'three'};

var key = map.keys.firstWhere((k) => map[k] == 'two', orElse: () => null);
print(key);


来源:https://stackoverflow.com/questions/52052241/how-to-get-map-keys-by-values-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!