Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore case while comparing string with keyvalue in the hashmap

I am trying to check if my hashmap key set contains the string 'buffSB.toString()'. But I wanted to compare ignoring case (upper or lower).

static StringBuilder buffSB = new StringBuilder(); 

buffSB.append(alphabet);

Map<String, String> pref =  new Datamatch().main();  // Getting the Hashmap from other class

if(pref.containsKey(buffSB.toString()))             //This is where I need to ignore case while searching string in the map key set 
  { 
      String val = pref.get(buffSB.toString());
  }

Any help will be greatly appreciated!!!

like image 518
Leyon Gudinho Avatar asked Nov 20 '15 14:11

Leyon Gudinho


People also ask

How do you compare strings to ignore cases?

The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.

Are Keys in HashMap case-sensitive?

Map is one of the most common data structures in Java, and String is one of the most common types for a map's key. By default, a map of this sort has case-sensitive keys.

Is map containsKey case-sensitive?

Map keys of type String are case-sensitive. Two keys that differ only by the case are considered unique and have corresponding distinct Map entries. Subsequently, the Map methods, including put , get , containsKey , and remove treat these keys as distinct.

Why do we prefer String as key in HashMap?

Since the String class is immutable, you cannot modify the value of a String once it is created. Therefore, it is recommended to use a String variable to hold keys in hash a map.


1 Answers

You can also try to use TreeMap which enable providing a comparator to its constructor:

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

see Case insensitive string as HashMap key

like image 148
jMounir Avatar answered Oct 25 '22 17:10

jMounir