Dart map with string key, compare with ignoring example

Does the map class in Dart have the ability to ignore the 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 comparative example, such as the comment above. What is the canonical way to do this in Darth?

+6
source share
4 answers

Cards in Dart have an internal method that compares keys for equality. As far as I know, you cannot change this for the default Map class. However, you can use a very similar LinkedHashMap kernel LinkedHashMap , which not only allows, but requires a key equality method. You can learn more about LinkedHashMaps at https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:collection.LinkedHashMap

 LinkedHashMap<String, String> map = new LinkedHashMap( (a, b) => a.toLowerCase() == b.toLowerCase(), (key) => key.toLowerCase().hashCode ); map['Foo'] = 'bar'; print(map['foo']); //bar 
+4
source

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

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

I really recommend finding a way to not do toUpperCase with every operation!

+4
source

You can use Dictionary .
But this is not a canonical way to do this in Darth.

 import "package:queries/collections.dart"; void main() { var dict = new Dictionary<String, int>(new IgnoreCaseComparer()); dict["MyKey"] = 42; var shouldBe42 = dict["mykey"]; print(shouldBe42); } class IgnoreCaseComparer implements IEqualityComparer { bool equals(Object a, Object b) { if (a is String && b is String) { return a.toLowerCase() == b.toLowerCase(); } return a == b; } int getHashCode(Object object) { if (object is String) { return object.toLowerCase().hashCode; } return object.hashCode; } } 

Output

 42 
0
source

You can also do this using the package:collection CanonicalizedMap class. This class is clearly designed to support maps with "canonical" versions of keys and is slightly more efficient than passing the usual equality method and hash code to a regular Map .

0
source

Source: https://habr.com/ru/post/980462/


All Articles