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?
Examples:

Set<String> nameSet = new Set<String>;
nameSet.add(srinu);
nameSet.add(SRINU);
nameSet.add(Srinu);

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;
                    break;
                }
            }
        }
        return isTrue;
    }

How to use above method?
if(!isStrExists(nameSet,'SRINU'))
    nameSet.add('SRINU');

5 comments:

  1. Excellent post!!! The future of cloud computing is on positive side. With most of the companies integrate Salesforce CRM to power their business; there is massive demand for Salesforce developers and administrators across the world. Salesforce Training Institutes in Chennai

    ReplyDelete
  2. In coming years, cloud computing is going to rule the world. The cloud based CRM tool provider like Salesforce have massive demand in the market. Thus talking Cloud Computing Training in Chennai from reputed Cloud Computing Courses will ensure bright career prospects for aspiring professionals.

    ReplyDelete
  3. Very interesting and good article, it is very useful to me... keep rocks.. thanks for sharing your valuable time and views....

    Salesforce Training in chennai | Salesforce Training in velachery

    ReplyDelete