New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :

Thursday 5 June 2014

Avoid duplicate string values in the collection 'Set' or 'Map Keys' while adding strings with different cases

When, Set allows duplicates?

Set<String> nameSet = new Set<String>;

Map<String,String> cityMap = new Map<String,String>;
cityMap .put('Newyork', USA);
cityMap .put('newyork',US);
cityMap .put('NEWYORK','America');

From the above examples, nameSet and cityMap allows all the three values because set and map key treat the values with different case as different values that means set string values are case-sensitive.

How to avoid?
Use the below method before adding string value to set or map key.

//Generic method to search a string from set of strings and which will ignore case-sensitive
public static Boolean isStrExists(Set<String> strSet,String searchStr) {
        Boolean isTrue = false;
        if(strSet != null && strSet.size() > 0) {
            for(String strVal : strSet) {
                if(strVal.equalsIgnoreCase(searchStr)) {
                    isTrue = true;
        return isTrue;

How to use above method?