Home > Net >  Using List as a key in map in Dart
Using List as a key in map in Dart

Time:02-07

Here is my Dart code

var mp = new Map();
  mp[[1,2]] = "Hi";
  mp[[3,5]] = "sir";
  mp.remove([3,5]);
  print(mp);

Output here is null

How can i access value at mp[[3,5]]?

CodePudding user response:

Two list instances containing the same elements is not equal to each other in Dart. This is the reason your example does not work.

If you want to create a Map which works like your example, you can use LinkedHashMap from dart:collection (basically the same when you are using Map()) to create an instance with its own definition of what it means for keys to be equal and how hashCode is calculated for a key.

So something like this if you want to have keys to be equal if the list contains the same elements in the same order. It should be noted it does not support nested lists:

import 'dart:collection';

void main() {
  final mp = LinkedHashMap<List<int>, String>(
    equals: (list1, list2) {
      if (list1.length != list2.length) {
        return false;
      }
      
      for (var i = 0; i < list1.length; i  ) {
        if (list1[i] != list2[i]) {
          return false;
        }
      }
      
      return true;
    },
    hashCode: Object.hashAll,
  );

  mp[[1, 2]] = "Hi";
  mp[[3, 5]] = "sir";
  mp.remove([3, 5]);
  print(mp); // {[1, 2]: Hi}
}

I should also add that this is really an inefficient way to do use maps and I am highly recommend to never use List as keys in maps.

CodePudding user response:

You add a list instance as a key to the Map object. You need the corresponding list instance to delete it again.

There are two ways to access

First;

  final mp = {};
  mp[[1,2]] = "Hi";
  mp[[3,5]] = "sir";
  mp.removeWhere((key, value) {
    if(key is List){
      return key.first == 3 && key[1] == 5;
    }
    return false;
  });

Second;

  final mp = {};
  final key = [3, 5];
  mp[[1,2]] = "Hi";
  mp[key] = "sir";
  mp.remove(key);
  •  Tags:  
  • Related