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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With