Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Map with String key, compare with ignore case

Tags:

dart

Does the Map class in Dart have a way to ignore case if the key is a string?

Eg.

var map = new Map<String, int>(/*MyComparerThatIgnoresCase*/);
map["MyKey"] = 42;
var shouldBe42 = map["mykey"];

In C# the Dictionary constructor takes a comparer like the comment above. What is the canonical way to do this in Dart?

like image 590
Jonas Kello Avatar asked Jan 03 '15 12:01

Jonas Kello


People also ask

How do you check if a map contains a key in Dart?

containsKey() function in Dart is used to check if a map contains the specific key sent as a parameter. map. containsKey() returns true if the map contains that key, otherwise it returns false .

Does case insensitive contain Dart?

There is no case-insensitive string compare function (or string equality function for that matter) in Dart.

Is map key case-sensitive?

Map is one of the most common data structures in Java, and String is one of the most common types for a map's key. By default, a map of this sort has case-sensitive keys.

How do I get the map value by key in Dart?

A Dart Map allows you to get value by key. What about getting key by value? Using the keys property and the firstWhere() method of the List class, we can get key by specifying value . The Dart method firstWhere() iterates over the entries and returns the first one that satisfies the criteria or condition.


2 Answers

The way to create a HashMap with a custom equals function (and corresponding custom hashCode function) is to use the optional parameters on the HashMap constructor:

new HashMap<String,Whatever>(equals: (a, b) => a.toUpperCase() == b.toUpperCase(),
                             hashCode: (a) => a.toUpperCase().hashCode);

I really, really recommend finding a way to not do the toUpperCase on every operation!

like image 199
lrn Avatar answered Oct 31 '22 03:10

lrn


You can also do this using package:collection's CanonicalizedMap class. This class is explicitly designed to support maps with "canonical" versions of keys, and is slightly more efficient than passing a custom equality and hash code method to a normal Map.

like image 21
Natalie Weizenbaum Avatar answered Oct 31 '22 04:10

Natalie Weizenbaum