I want to implement a case insensitive hash map. This question by itself isn't new, but I wanted to add extra functionality and don't know what general direction to take. I want the client to be able to do something like this:
boolean preserve_case = true;
Map<String, MyClass> maplet = new CaseInsensitiveHashMap<MyClass>(preserve_case); // If the client enters true at construction, then the put, get, and remove methods should still be case insensitive, but the entry and key sets should preserve the case that the client used when calling put.
maplet.put("FoO", my_class);
MyClass bar = maplet.get("foo"); // Should return a reference to my_class
Set<Entry<String, MyClass>> case_sensitive_set = maplet.entrySet(); // Since the client input true to preserve order, this entry set should be ["FoO"=my_class.toString()]
I can handle most of this pretty well; I simply keep a HashMap
on the backend. When a client puts anything in, I uppercase the key before adding it to the map.
I'm just having a hard time writing the keySet()
and entrySet()
methods. I want the returned entry set and key set to be backed by the map, as is the standard with Java maps.
However, the only way I can think of handling this is to create a second backing data structure, something like a preserved_case_map
, which contains the input.toUpperCase()
=> input as key value pairs. When the client calls for the entrySet()
(or keySet()
), I can construct the returned entry set by looping through the preserved_case_map
. The problem here is that the returned entry set will not be modified if I make changes to the HashMap
, unless I'm misunderstanding something...
Let me know if this makes sense, or if I'm convoluting a simple situation.
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.
A wrapper around the std::collections::HashMap that uses case-insensitive Strings for keys.
Always remember that both keywords and identifiers in a Map are case-sensitive.
Class LinkedCaseInsensitiveMap<V>LinkedHashMap variant that stores String keys in a case-insensitive manner, for example for key-based access in a results table. Preserves the original order as well as the original casing of keys, while allowing for contains, get and remove calls with any case of key.
You could use a TreeMap with case insensitive comparator. The TreeMap will use the comparator to compare keys in a case-insensitive way:
Map<String, Integer> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
map.put("Foo", 1);
map.put("fOo", 2);
System.out.println(map.get("foo")); // prints 2
System.out.println(map.keySet()); // prints [Foo]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With