loganrussell48
loganrussell48

Reputation: 1864

Is it possible to make a TreeMap from a Map literal?

I have a Map literal, an I want it to be a TreeMap, but by default I believe it's a LinkedHashMap. Casting a LinkedHashMap to a TreeMap won't work as it's not a subtype.

Basically, I'm looking for the simplest way to make this work:

var map = <int, int>{for(int i = 0; i < intervals.length; i++) intervals[i][0] : i} as SplayTreeMap;

As mentioned before, casting as SplayTreeMap won't work as they types don't align.

Thanks much in advance

Upvotes: 0

Views: 423

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17113

Use the SplayTreeMap.from constructor to create a SplayTreeMap. There isn't any way to cast it as you said.

Remove the as from your current code and add this to get your SplayTreeMap:

var newMap = SplayTreeMap.from(map);

Depending on your key type and your use case, you can pass compare and isValidKey parameters as well. Full constructor definition:

SplayTreeMap<K, V>.from(
  Map other,
  [int compare(
    K key1,
    K key2
  ),
  bool isValidKey(
    dynamic potentialKey
  )]
)

Upvotes: 1

Related Questions