Saturday, October 23, 2010

Java Pearls: case-insensitive Map?

Here's one more thing I did not know until very recently: how to get a Map with String keys that allows case-insensitive access? Or, case-insensitive membership checks. One typical use case is to handle case-insensitive entities such as names of HTML tags.

One obvious way to do this is to canonicalize keys by lower-casing (or upper-casing) keys both when inserted and when doing lookups. But this is actually not the only way to do this: there is a very simple JDK-provided alternative:


  Map<String,Object> tags = new TreeMap<String,Object>
(String.CASE_INSENSITIVE_ORDER);

and that's it; you can access values with any combination of casing. Similarly you can also create TreeSets for basic inclusion checks.

I hope this is something that most Java developers know and I had just somehow missed. But if not, here it is in case you happen to need such access.

ps. For what it's worth, the main reason I had missed this being a possibility was that I always thought comparator given to TreeMap and TreeSet would only be used for ordering. But thinking about it a bit more, this makes more sense; since comparisons must be done anyway (to find location of an entry to find or insert), why not use "equals" return value of comparator for something.

blog comments powered by Disqus

Sponsored By


Related Blogs

(by Author (topics))

Powered By

About me

  • I am known as Cowtowncoder
  • Contact me at@yahoo.com
Check my profile to learn more.