Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore the case sensitive when we look for a key in the Map? [duplicate]

Tags:

java

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

like image 289
Kathir Avatar asked Aug 13 '12 07:08

Kathir


2 Answers

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
like image 176
dacwe Avatar answered Sep 19 '22 20:09

dacwe


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.

like image 25
Heiko Schmitz Avatar answered Sep 17 '22 20:09

Heiko Schmitz