Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java case-insensitive map with null key [duplicate]

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.

like image 386
Gilo Avatar asked Jan 02 '18 17:01

Gilo


People also ask

Is map get case insensitive Java?

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.

IS NULL case-sensitive in Java?

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.

Is map containsKey case-sensitive?

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.

Is LinkedHashMap case-sensitive?

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.


2 Answers

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.

like image 71
Henrik Aasted Sørensen Avatar answered Sep 20 '22 18:09

Henrik Aasted Sørensen


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.

like image 29
Shubhendu Pramanik Avatar answered Sep 18 '22 18:09

Shubhendu Pramanik