How to have a Map<String, ?> get and put ignoring case?

How to have a Map<String, ?> get and put ignoring case?

If you want to create a Map in Java where the keys are case-insensitive strings, and you want to perform get and put operations without considering the case of the keys, you can achieve this by using a custom implementation of the Map interface. One common approach is to use a TreeMap with a custom Comparator that compares keys in a case-insensitive manner. Here's an example of how you can do this:

import java.util.Comparator; import java.util.Map; import java.util.TreeMap; public class CaseInsensitiveMap<V> { private final Map<String, V> map; public CaseInsensitiveMap() { // Create a TreeMap with a custom comparator for case-insensitive comparison this.map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); } // Methods to delegate to the underlying map public V get(String key) { return map.get(key); } public V put(String key, V value) { return map.put(key, value); } // Add other Map methods as needed public static void main(String[] args) { CaseInsensitiveMap<String> caseInsensitiveMap = new CaseInsensitiveMap<>(); caseInsensitiveMap.put("Key1", "Value1"); caseInsensitiveMap.put("key2", "Value2"); System.out.println(caseInsensitiveMap.get("KEY1")); // Output: Value1 System.out.println(caseInsensitiveMap.get("KeY2")); // Output: Value2 } } 

In this example:

  • We create a CaseInsensitiveMap class that wraps a TreeMap with a custom comparator (String.CASE_INSENSITIVE_ORDER) for case-insensitive key comparison.

  • The get and put methods delegate to the underlying map, which performs the operations in a case-insensitive manner.

  • You can add more methods to the CaseInsensitiveMap class as needed, depending on the functionality you require.

By using this custom CaseInsensitiveMap, you can store and retrieve key-value pairs in a case-insensitive manner. When you retrieve a value using get, it will match the key regardless of the case. Similarly, when you put a key-value pair using put, it will handle the keys in a case-insensitive way.


More Tags

subnet alignment routes android-7.0-nougat kestrel-http-server python-3.6 guice google-sheets-macros axis-labels flowlayoutpanel

More Java Questions

More Stoichiometry Calculators

More Pregnancy Calculators

More Geometry Calculators

More Cat Calculators