13

Possible Duplicate:
Is there a good way to have a Map<String, ?> get and put ignoring case?

How to ignore case sensitive when searching a key in the java.util.Map?

I want to know whether we can look up for a key in the map by ignoring the case.

Example,
   Map<String, Integer> lookup = new HashMap<String, Integer>();   
   lookup.put("one", 1);   
   lookup.put("two", 2);   
   lookup.put("three", 3); 

The user input might be "ONE" or "one". in such a case instead of converting the user input to lowercase. is there is any way to ignore the key sensitive via any methods?

Thanks, Kathir

Community
  • 1
  • 1
Kathir
  • 2,545
  • 12
  • 34
  • 62

2 Answers2

60

Why not use a TreeMap instead of HashMap, then you could specify a Comparator with a case insensitive order (String.CASE_INSENSITIVE_ORDER):

public static void main(String[] args) throws Exception {

    Map<String, Integer> lookup = 
        new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);

    lookup.put("One", 1);
    lookup.put("tWo", 2);
    lookup.put("thrEE", 3);

    System.out.println(lookup.get("Two"));
    System.out.println(lookup.get("three"));
}

Outputs:

2
3
dacwe
  • 42,413
  • 12
  • 112
  • 138
  • 2
    This is really looks good and great...Thanks a lot... – Kathir Aug 13 '12 at 07:24
  • 3
    hashMap performance is O(1) & TreeMap performance O(log(n)) read this Question http://stackoverflow.com/questions/2889777/difference-between-hashmap-linkedhashmap-and-treemap – Ammar Bozorgvar Aug 16 '16 at 14:15
3

HashMap uses the key's equals(Object) method (in combination with hashCode()), and String.equals() is case-sensitive. So if you want a case-insensitive key, you have to define your own key class with a proper equals() and hashCode(). In total, is possibly easier to use toLowerCase() on all key strings.

Heiko Schmitz
  • 290
  • 1
  • 4