14

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.

5

3 Answers 3

31

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Worth noting that by using a TreeMap, get, put and remove operations will be O(log(n))
8

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.

Comments

5

If you would prefer not using external libraries, you could make your own wrapper for String.CASE_INSENSITIVE_ORDER that sorts nulls in a predictable way:

 NavigableMap<String,String> m = new TreeMap(
    new Comparator<String>() {
        public int compare(String s1, String s2) {
            if (s1 == null && s2 == null) return 0;
            if (s1 != null && s2 != null) {
                return String.CASE_INSENSITIVE_ORDER.compare(s1, s2);
            }
            return s1 == null ? -1 : 1;
        }
    }
 );

Demo.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.