Friday, April 5, 2013

Java - Case insensitive Map

You know keys in the java.util.HashMap are case sensitive. It means you can keep both "abc" and "ABC" as keys in the same map.

See this example.
public static void main(String[] args) {

  Map<String, String> map = new HashMap<String, String>();
  map.put("abc", "abc");
  map.put("xyz", "xyz");
  map.put("ABC", "ABC");

  System.out.println(map);
}
Output
{ABC=ABC, abc=abc, xyz=xyz}

But some times you may need to have a case insensitive map.
In such case you can use the java java.util.TreeMap, which let you to pass a Comparator to it's constructor.

See below example
public static void main(String[] args) {

  Map<String, String> map = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
  map.put("abc", "abc");
  map.put("xyz", "xyz");
  map.put("ABC", "ABC");

  System.out.println(map);
}
Output
{abc=ABC, xyz=xyz}

Note:
Another option is to write your own class by extending the HashMap class and overriding the get() and put() methods.

3 comments:

  1. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
    python course institute in bangalore
    python Course in bangalore
    python training institute in bangalore

    ReplyDelete
  2. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..
    python interview questions and answers
    python tutorials
    python course institute in electronic city

    ReplyDelete