Is there a Map implementation in Java that will use case-insensitive String matching for the key, but also supports the null key? I know that
new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER)
supports case-insensitive matching of String keys, but it doesn't support the null key.
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.
Null is a reserved keyword in the Java programming language. It's technically an object literal similar to True or False. Null is case sensitive, like any other keyword in Java.
I want to know whether a particular key is present in a HashMap, so i am using containsKey(key) method. But it is case sensitive ie it does not returns true if there is a key with Name and i am searching for name.
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. Does not support null keys.
If you're on Java 8, the following will create a null-compatible, case-insensitive TreeMap
:
Comparator<String> cmp = Comparator.nullsFirst(String.CASE_INSENSITIVE_ORDER);
TreeMap<String, String> map = new TreeMap<>(cmp);
No external libraries needed.
You can use CaseInsensitiveMap for this. This will fulfill your requirement. It is case-insensitive as well as supports null keys.
From the doc
A case-insensitive Map. Before keys are added to the map or compared to other existing keys, they are converted to all lowercase in a locale-independent fashion by using information from the Unicode data file.
Null keys are supported.
The keySet() method returns all lowercase keys, or nulls.
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