Search code examples
javastringhashmapswitch-statementequals

Check 2 strings without case sensitivity or use equalsIgnoreCase method


I have some inputted String String usrInput; that user could import some string once into App without any case-sensitivity policy like: "start","Start","START","end" ,"END" and etc.

And I have a Map that i inserted my strings for example "start" into that and put it into HashMap<String, String> myMap:

Map<String, String> listOfActions = new HashMap<>();
listOfActions.put(myStr, myStr);

Now I want to check listOfActions members to get for example "start" filed in every case model ("start","Start","START") , currently I do like below:

if (listOfActions.containsKey(usrInput.toUpperCase())
        || listOfActions.containsKey(usrInput.toLowerCase())) {
    /// some do
}

So I want to know:

1. Is there any way to get String value without case-sensitivity? I will also add this here I couldn't use equalsIgnoreCase() method for get items from Map because its return Boolean.

2. I have similar problem in switch-case statements to check 2 string equality without case-sensitivity.


Solution

  • You can use

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

    Other solutions can be Apache's CaseInsensitiveMap or Spring's LinkedCaseInsensitiveMap.

    Please see https://www.baeldung.com/java-map-with-case-insensitive-keys for more details about these solutions.