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

There are multiple ways to achieve this
(1) We can use a TreeMap instead of HashMap, then specify a Comparator with a case insensitive order (String.CASE_INSENSITIVE_ORDER)
package in.softcaretech;
import java.util.Map;
import java.util.TreeMap;
public class TreeMapDemo {
public static void main (String args[]){
Map<String, String> studentMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
studentMap.put("Amit", "Audi");
studentMap.put("Nilesh", "BMW");
System.out.println("Searchnig AMIT Key from map:" + studentMap.get("AMIT"));
System.out.println("Searchnig amit Key from map:" + studentMap.get("amit"));
}
}
(2) You can write a wrapper map class with custom put and get methods (converting keys to lower case order).
package in.softcaretech;
import java.util.HashMap;
public class CustomMap extends HashMap<String, String>{
@Override
public String put(String key, String value) {
return super.put(key.toLowerCase(), value);
}
// not @Override because that would require the key parameter to be of type Object
public String get(String key) {
return super.get(key.toLowerCase());
}
}
package in.softcaretech;
import java.util.Map;
public class CustomMaptest {
public static void main(String[] args) {
CustomMap studentMap = new CustomMap();
studentMap.put("Amit", "Audi");
studentMap.put("Nilesh", "BMW");
System.out.println("Searchnig AMIT Key from map:" + studentMap.get("AMIT"));
System.out.println("Searchnig amit Key from map:" + studentMap.get("amit"));
}
}
(3) You can use apache collections package (org.apache.commons.collections.map.CaseInsensitiveMap):
You need to download jar file from apache website and add it to project class path, if you are using maven based project than add dependency as below
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
package in.softcaretech;
import java.util.Map;
import org.apache.commons.collections4.map.CaseInsensitiveMap;
public class CaseInsensitiveMapDemo {
public static void main (String args[]){
Map<String,String> studentMap = new CaseInsensitiveMap<String,String>();
studentMap.put("Amit", "Audi");
studentMap.put("Nilesh", "BMW");
System.out.println("Searchnig AMIT Key from map:" + studentMap.get("AMIT"));
System.out.println("Searchnig amit Key from map:" + studentMap.get("amit"));
}
}
There might be other ways ... Suggestions and comments are welcome.