Monday, 19 December 2016

Success Story of : Jennifer Wobser


Welcome to my 3rd Salesforce Success Story series. This series is focused on success story and to inspire/encourage new user/Developer. And why we should join our local Salesforce Developer/User group.



1) Your Job Title
 
I'm starting a new job in the next two weeks, but for now you can list me as:
Sr Consultant & Salesforce SME for Dazeworks.com (Amit :- All the best for your new job)


2) Your success Story   

My journey with Salesforce is quite unique as most people recognize my twitter handle @crmsalesgem from 2014 when Salesforce1 was a big deal. The funny part is, that wasn't my first time working with Salesforce mobile. I was actually already an admin when Salesforce mobile was in its infancy in 2004-05. Here's the proof...




My roots with data actually span almost 3 decades, and the first time I built a Salesforce demo org was 15 yrs ago! I am a 100% self-taught admin, and this wasn't by choice! I can remember Salesforce before we had user groups/communities, AppExchange, Certifications, and Chatter! Back then, if you loved Salesforce, you learned it out of passion & necessity for your job!


My story starts here...


I have been working with data since 1988, and I guess you could say I was way ahead of my time. I'd worked several jobs collecting, cleaning, and building databases. In the 1990's people were amazed I understood spreadsheets and would often pay me to set up a system to collect data in the earliest versions of Excel and Access available. My favorite pre-Salesforce data job was building and managing the first online scholarship database for the State of Arkansas 1997-2001.

I eventually landed at a Bio-pharmaceutical company as a sales rep alongside my mother in 2001. I loved working with my mother - I helped her with data and she helped me learn sales! Within my first year in sales, the executives and sales managers were puzzled as to why my sales were so high when I was brand new to the business. I explained I had created an Access database using my daily sales & customer lists to track my customers' buying patterns and identify the low hanging fruit. This home made database eventually led to my first demo org of Salesforce that I set up in 2002 while I was comparing my Access database to current CRM software available on the market.

This is a screenshot with dummy data of my first Salesforce prototype:






 This prototype impressed our CIO, so I was immediately plucked out of sales and given a role in IT as Salesforce Administrator and Data Analyst. Our company had to wait until 2004 to actually buy Salesforce as we were one of the first companies to be on the pilot for custom objects to use with our ERP. In addition, in the land before iPhones, our company was one of the first five customers set up to use Salesforce with Blackberries. The Sendia app we used later became Salesforce Mobile and Salesforce1. (as seen in top pic)

Here I am with my mom and our sales manager circa 2004 - the same month I found out I would be moving from Sales to Salesforce Administrator!




 Unfortunately, I don't have any pics of my first Dreamforce in 2004. Back then, you had to actually carry your digital camera with you to take pics. I really wish I had a camera back then! I'd go back and take a pic as Marc Benioff personally thanked me for becoming a customer! Can you imagine? Marc and Parker used to freely walk around and talk to us with no security in 2004. Of course, we were at the top of the Hilton with about 800 people - to think I thought that Dreamforce was huge! I can remember being so scared to talk about being a new customer in front of about 50 people in a session there. Well, it wasn't as bad as I thought. In fact, I found that I loved teaching others what I learned about Salesforce, and I have now been a speaker at every Dreamforce 2004-16!

My favorite speaking engagement was the first Salesforce Ohana celebration in 2005 at the Summer '05 Release Party in San Francisco! Salesforce flew me out to San Francisco so I could showcase the custom objects I built for our ERP data. I remember how amazed people were to see that I build custom objects and bridge objects for Open Orders, Line Items, and Invoices!





 Fast forward to 2016, and I am now a mother to my 6 year old beautiful boy-Joshua, Salesforce MVP since Jan 2014, Certified Salesforce Administrator (first 250 certified in 2008), over 100 Trailhead Badges, and above all else, I am passionate about helping others in our Salesforce community.

* I think it's important to note that due to a family illness, I left my 13 yr admin job to join to the Salesforce consulting world in 2015. I am so very grateful for our Salesforce community as they have been a support system for me during my time of need. When my father became ill (he recently passed away on October 13, 2016), both Salesforce and my MVP colleagues were kind enough to give me consulting work to keep me on my financial feet! What other software company/community has such an amazing support system both professionally and personally? Ask yourself that question before you ever consider leaving a Salesforce profession!



 (Amit :- Jennifer Wobser story is really awesome. Seriously, We can write a novel on her  what she have learned over the last 15 years)


 3) Why we Should Join a Salesforce User/Developer Group


A long time ago, In a land far far away...we didn't have Salesforce User Groups! I remember feeling very alone in my learning. I loved Salesforce so much, and I longed to meet other admins like me outside of Dreamforce. Then, I met Erica Kuhl, and she helped me at the same time she was working very hard to build our first user groups!

Can you imagine? Our little online posting board in this pic eventually blossomed into the user groups we have today all over the world!




 If you are not limited by your location, I recommend everyone in the Salesforce community join their local user group. A support system for anything we do will only make us better. These user groups are a great way to learn and meet other like-minded individuals. Each of us can accomplish so more amazing things as a group rather than by ourselves! For example, in my Springfield, MO user group, we have meetings based on what our group votes on. Some of the best group meetings we have had were the following:
  1.     Worked through difficult Trailhead badges as a group that we couldn't do alone
  2.     Completed the Drucker School Trailhead Modules as a group so that we could all order the certificate of completion before the $25 fee was active
  3.     Discuss, show pictures, and bring back Swag for events such as Dreamforce, TrailheadX, and Midwest Dreamin for the members of the group that couldn't attend

If I didn't have my local user group, the above wouldn't be possible!



4) Advice for new Salesforce Developer

It has taken me 15 years to learn that in the Salesforce community, it is who you know vs what you know. Most of us can learn the tech side fairly well, earn badges, and gain certifications. Finding the right job and/or meeting friends to support us in our jobs can be a bit of a challenge. As an introvert myself, I have learned many ways to meet people using social media. Meeting people and knowing you are part of our community/something bigger is the key to your success. For example, I had known Cheryl Feldman in passing since 2005, but we were able to reconnect via Twitter in 2013. Now she is one of my best friends both inside and outside of the Salesforce world!

This pic sums up how great it is to have a 'Salesforce Bestie' who understands you!




 Here are some tips that anyone in our community can use to expand their network of people:
  •     Join your local user group! This gives you an opportunity to meet other Salesforce people like yourself plus partners, companies that use Salesforce, and guest speakers. I know a lot of people who found their 'Dream Job' by meeting someone at a user group.
  •     Offer to meet up with smaller groups within your local user group between meetings! This is how #BBQforce was started - a handful of us decided to get together the night before our user groups and talk Salesforce while eating BBQ. Now we are all friends for life! 



  •    Be active on the Salesforce Community - post questions, answer questions, join group discussions etc.
  •    Be actively engaged on Twitter - follow all of the Salesforce handles such as @salesforce, @dreamforce, @trailhead, @salesforceadmns, @salesforcedevs, etc. This is also the best way to stay informed of the latest news and events!
  •    Join every Salesforce web meeting/webinar available that your schedules allow - these are great opportunities to hear Salesforce employees and customers talk about their experience. You can also become familiar with names of people and companies this way.
  •    Offer to speak at your local user group, be a guest speaker on a podcast/webinar, write a blog, and/or contribute to the Salesforce community in any way possible! Whether you are the mentor or the mentee, these relationships facilitate success!
  •     Attend events such as Dreamforce and regional events like Tahoe Dreamin, Snowforce, SouthEast Dreaming, Midwest Dreamin, etc. Events are great because you get to meet people and learn as a group at the same time! I can say that I learn a lot in group sessions as well as personal conversations with people I meet in between sessions when I attend these.


 5) Trailhead badges
 
112 thanks to #trailheadathon - I am totally addicted! I am so happy to have the new Trailhead Profiles! For the first time in 15 years, I can actually show my admin skills with badges rather than just telling a story about how long I've been working with the Salesforce platform!





Follow Jennifer Wobser  on:
Twitter : 
@crmsalesgem


 If you want to share your Salesforce Success Story, Please feel free to drop me an email :- amit.salesforce21@gmail.com

<<PREVIOUS       NEXT>>


Thanks
Amit Chaudhary
@amit_sfdc




Wednesday, 14 December 2016

Test Class for Email Service | Test class for InboundEmail


In last month post we created the "Apex Email Service" . Now in this post we will get to know how to write the test class for Apex Email Service.


global class EmailServiceExample implements Messaging.InboundEmailHandler 
{
 global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,Messaging.InboundEnvelope env)
 {
  // Create an InboundEmailResult object for returning the result of the Apex Email Service
  Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
  try 
  {
   List<Contact> contList= [SELECT Id, Name, Email FROM Contact WHERE Email = :email.fromAddress LIMIT 1];
   Task taskObj = new Task();
   taskObj.Description =  email.plainTextBody;
   taskObj.Priority = 'Normal';
   taskObj.Status = 'Inbound Email';
   taskObj.Subject = email.subject;
   taskObj.IsReminderSet = true;
   taskObj.ReminderDateTime = System.now()+1;
   if(contList.size()>0)
   {
    taskObj.WhoId =  contList[0].Id;
   }    
   insert taskObj;    
  }
  catch (Exception e) 
  {
     System.debug('Exception : ' + e);
  }
  result.success = true;
  return result;
 }
}


Test Class

@isTest
private class EmailServiceExampleTest
{
    static testMethod void testUnsubscribe() 
    {
       // Create a new email and envelope object.    
       
       Messaging.InboundEmail email = new Messaging.InboundEmail() ;
       Messaging.InboundEnvelope env    = new Messaging.InboundEnvelope();
    
       // Create Test record.
       Contact cont = new Contact(firstName='john', lastName='smith', Email='test@test.com', HasOptedOutOfEmail=false);
       insert cont ;
       
       // Test with the subject that matches the unsubscribe statement.
       email.subject = 'Test Contact Email';
       //email.plainTextBody = 'Test Contact Email';
       env.fromAddress = 'test@test.com';        EmailServiceExample obj= new EmailServiceExample();        obj.handleInboundEmail(email, env );                                  }       }


 Let us know if this will help you

Thanks,
Amit Chaudhary


Friday, 2 December 2016

Success Story of : Sharif Shaalan


Welcome to my 2nd Salesforce Success Story series. This series is focused on success story and to inspire/encourage new user/Developer. And why we should join our local Salesforce Developer/User group.






1) Your Job Title

Technical Architect Manager, roundCorner

2) Your success Story   
 
Sharif :- I have a sales background and had always been in sales positions as a top seller in the companies I worked for.  This is where I was first introduced to Salesforce, as a user at a few of the companies I worked for.  In 2007 I found myself doing inside cold calling sales and using Salesforce once again.  I was promoted to Sales trainer in order to train the new hires in the methods that I used to become a top seller.  On my first day off of the phones as the trainer the Salesforce Admin for the company quit.  The CEO called me into the office and said, “you are now the Salesforce admin too”.  “Sure” I responded and that day my Journey really started. I spent the next two years learning Salesforce the best way in my opinion, hands on!  I wore many hats as I became the CEO’s right hand man and helped expand the team from 12 reps to over 100 reps increasing revenue from inside sales exponentially.  In 2009 the company sent me to Dreamforce, and that is when I realized the true potential of the platform.  I signed up for as many hands on sessions as possible and came back with a ton of quick wins for the team.   The best thing that came out of that visit was my introduction to certifications.  I spent the next few months after Dreamforce studying for my Admin Cert and passed my exam early 2010.
As soon as I added “Certified Salesforce Admin” to my LinkedIn profile I was bombarded with job and contracting offers in the NYC area.  With a few good contracting offers I decided to start my own consulting company, Agile Cloud Consulting LLC.  I had a talk with the CEO of the company I worked for and he agreed to become a client rather than me leaving altogether.  I spent the rest of 2010 with a lot of work and my company was doing very well.
In early 2011 one of my clients was roundCorner.  I contracted with roundCorner as one of my clients until late 2011 when they gave me an offer I couldn’t refuse to come on as a Principal Consultant.  I am still with roundCorner and am now a Technical Architect Manager at the company.  Along the way I was a product manager and now have 7 Certifications.  I am also a 4x Salesforce MVP. ( Amit:- your story is really motivating )

3) Why we Should Join a Salesforce User/Developer Group

Sharif :- Joining a user group allows you to stay up to date on the latest and greatest salesforce has to offer as well as meeting peers in your geographical region. (Amit:- That true , User group is one of the best place where we can know about latest release or feature )

4) Advice for new Salesforce Developer

Sharif :- Go through the trailhead modules! even if you're coding you need to be sharp on the declarative side to implement best practices. ( Amit:- Day by day i am become a fan of TraillHead. Now learning in salesforce to much easy as compare to our time )

5) Trailhead badges 

Sharif :- I have 13 badges, i've been slacking : ) ( Amit:- Start using Trailhead :)  )


Follow Sharif on:
Twitter:
@sharif_shaalan 
 Blog :- yappexchange.com

 

 If you want to share your Salesforce Success Story, Please feel free to drop me an email :- amit.salesforce21@gmail.com


<<PREVIOUS       NEXT>>



Thanks
Amit Chaudhary
Twitter @amit_sfdc



Friday, 18 November 2016

Success Story of : Amy Oplinger


Welcome to my First Salesforce Success Story series. This series is focused on success story and to inspire/encourage new user/Developer. And why we should join our local Salesforce Developer/User group.





1) Your Job Title

Amy :
- Consultant, Coastal Cloud

2) Your success Story

Amy:-
I used SFDC as an end user for about 5 years in my sales career. I was lucky enough to work at a company looking to implement a CRM, and I suggested Salesforce. They made me part of the implementation team and their Super User! Learning more about the back end of Salesforce scratched an itch in my brain that sales by itself never could. I went to another company in a sales capacity, and quickly saw their SFDC instance was a mess. I took it upon myself to write up the issues I saw, how i could fix it, and how it would benefit them. My boss agreed, and made me their Administrator on the spot! While splitting my time between Admin and Sales, it became clear to me that I wanted my day to be filled with 100% Salesforce. I spoke to my manager, and because they were small, they couldn’t support a FT Admin. So, I graciously resigned, with the goal of pursuing my Salesforce dream. I put my resume online that day, and within 24 hours, I was contacted by a recruiter and immediately placed on the SFDC team at GE Lighting in Cleveland as a consultant. It was there I met the person who would become my Salesforce mentor! Learning from my mentor at GE was like being in Salesforce bootcamp; I learned a great deal very quickly. I am now happily in another consultant role, where I gain exposure to many different instances of Salesforce, each with their own unique needs. My dream of working 100% of my day in the platform came true very quickly, once I took the leap to pursue it!    

3) Why we Should Join a Salesforce User/Developer Group

Amy:-
In addition to the online Success Community, go to the Developer UG meeting. Go to the regular UG meeting. Go to the WIT UG meetings(yes, men are welcomed!)- anything to connect in person with others on the platform. These are people you will soon lean on and learn from! 
(Amit :- Totally agree with Amy. We can search our near by Salesforce Developer group from here )

4) Advice for new Salesforce Developer

Amy:-
I would tell anyone new in the field to embrace the community- admins and devs alike! You have the Success community, User Groups, and Twitter to connect with fellow Salesforcians. Use each avenue to its fullest! Don't be afraid to ask questions. I also feel it’s very important to seek out a mentor..they can talk you through when you are having doubts or feeling overwhelmed! I was lucky enough to work with mine, but the success community is so supportive, you are bound to also find many virtual mentors! (Amit:- Also please start using trailhead for leaning and developer forum for any question in salesforce)


5) Trailhead badges

137 ( Amit :- OMG )


Follow Amy on:
Twitter:
@salesforceamy
Success Profile :- https://success.salesforce.com/ProfileCertificationsAndBadges?u=0053000000BKF1zAAH



If you want to share your Salesforce Success Story, Please feel free to drop me an email :- amit.salesforce21@gmail.com

                                                                                                                    NEXT >>


Thanks
Amit Chaudhary
Twitter @amit_sfdc





Tuesday, 15 November 2016

Apex Email Service | InboundEmail Object | Messaging.InboundEmailHandler in salesforce


Email Service

Email service is special processes that use Apex classes to process incoming email messages. When you set up an email service, we need to generate a special email address in which salesforce will receive your emails. For same we need to create one apex class to implement Messaging.InboundEmailHandler interface . The email services will then invoke a handleInboundEmail method on the Apex class whenever an email is received on the email address.


NOTE:- Before creating email services we need to create Apex classes that implement the Messaging.InboundEmailHandler interface.


STEP 1:- Create one Apex class with Messaging.InboundEmailHandler

global class EmailServiceExample implements Messaging.InboundEmailHandler 
{
 global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,Messaging.InboundEnvelope env)
 {
  // Create an InboundEmailResult object for returning the result of the Apex Email Service
  Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
  try 
  {
   List<Contact> contList= [SELECT Id, Name, Email FROM Contact WHERE Email = :email.fromAddress LIMIT 1];
   Task taskObj = new Task();
   taskObj.Description =  email.plainTextBody;
   taskObj.Priority = 'Normal';
   taskObj.Status = 'Inbound Email';
   taskObj.Subject = email.subject;
   taskObj.IsReminderSet = true;
   taskObj.ReminderDateTime = System.now()+1;
   if(contList.size()>0)
   {
    taskObj.WhoId =  contList[0].Id;
   }    
   insert taskObj;    
  }
  catch (Exception e) 
  {
     System.debug('Exception : ' + e);
  }
  result.success = true;
  return result;
 }
}


STEP 2 :- Setup Email service

1) Go to Setup -->Develop->Email Services



2) Click on New Email Service
3) Then complete all below information



4) then click on SAVE button.

STEP 3 :- Generate an email address

1) Click on "New Email Address" button

2) Then add all below detail

 3) Then click on SAVE button.

 You will see a new email address that salesforce will monitor, emails received on this address will trigger the associated Apex code.



STEP 4 :- Testing of email service

1) Create one contact with sender email address.
2) Then send email from given email domain to same email address.



Please check next post for Apex Email Service Test class

Thanks,
Amit Chaudhary









Wednesday, 26 October 2016

First Farmington Hills Salesforce Developer Meetup




Finally we completed our first Farmington Hills Saleforce Developer Meetup on 19 Oct 2016. Our first meetup was bit more informal and we got chance to know each other and about Dreamforce 2016 also. More then 16+ Developers joined us in our first meetup ( I am very happy as more then 16+ Developers joined in our first meetup as i am also new in USA ) .

Thanks you Salesforce and Brad Mosharo to provide me a chance to become the Co-Organizer of "Farmington Hills Salesforce Developer Meetup"


Special Thanks to Eric Dreshfield­ to join us online in our first meetup. He gave some tips how to make a meetup as successful and also shared his experience about Dreamforce 2016.


Facebook Page :- https://www.facebook.com/FarmingtonHillsSfdcdug/
Meetup Link :- http://www.meetup.com/Farmington-Hills-Salesforce-Developer-Meetup/
Twitter Tag :- #FarmingtonHillsSFDCdug


Some Pic of our First Meetup

First Meetup Place :- 32737 W. Twelve Mile Rd, Farmington, MI, Farmington, MI,USA




















Thanks,
Amit Chaudhary



 

Friday, 14 October 2016

Sales Cloud and Service Cloud



Sales Cloud :-
“When we develop product in force.com for sales then it comes in Sales Cloud Ex: - Account, Contacts, and Lead”. In different Words “ we are able to say that The Sales Cloud from salesforce.com is that the world's #1 sales application. It provides reps, managers, and execs everything they have to attach with customers and focus on what is important —more selling and fewer administration. It helps you close a lot of deals - quicker, gain period of time visibility into sales, and connect with today's social customers”.


Service Cloud :-When we need to supply some facility and additionally provides support to the clients then it comes in service Cloud. Ex: - create cases is that the example of Service Cloud within which consumer write his problem into cases rather than decision.

In different words “In service cloud when we sales product to consumer then we provides the various different types of facilities to consumer which will be helpful to consumer just like call center. In call center ,client will create a decision and ask his problem regarding product and might notice the higher answer about his problem“.


Difference between Sales Cloud and service Cloud:-

1. "Sales Cloud" refers to the "sales" module in salesforce.com. It includes Leads, Accounts, Contacts, Contracts, Opportunities, Products, price books, Quotes, and Campaigns (limits apply). It includes options like Web-to-lead to support online lead capture, with auto-response rules. it's designed to be a start-to-end setup for the entire sales process; you utilize this to help generate revenue.

While “Service Cloud" refers to the "service" (as in "customer service") module in salesforce.com. It includes Accounts, Contacts, Cases, and Solutions. It additionally encompasses features like the public knowledge base, Web-to-case, call center, and the Self-Service Portal, additionally as customer service automation (e.g. escalation rules, assignment rules). it's designed to permit you to support past, current, and future clients' requests for help with a product, service, and billing. you utilize this to help make people happy.

2. Sales Cloud Implements Sales and marketing whereas Service cloud implements Salesforce knowledge.

3. Sales Cloud ,A great solution for small and worth oriented mid-sized sales groups that need to quickly and cost effectively deploy Salesforce whereas Service Cloud   provides customer Support to the shoppers and giving you the tools to provide a better customer expertise for your clients.

 4. Sales Cloud provides you the flexibility to open Cases (issues) and relate them to Accounts, Contacts; etc. whereas The Service Cloud could be a superset of Sales Cloud, that means you get everything that's in Sales Cloud and some other features.

5. once we develop product in force.com for sales then it comes in Sales Cloud Ex: - Account, Contacts, and Lead. whereas when we need to provide some facility and additionally provides support to the clients then it comes in service Cloud. Ex: - produce cases is the example of Service Cloud in which client write his problem into cases instead of decision.




Functions in the Sales Cloud
If you’re presently using or are implementing salesforce.com’s Sales Cloud, you've got the foundation necessary to capture and resolve client questions or problems. the essential functionality includes:

Cases—you will track client inquiries, escalate problems requiring specialized support and monitor your agent’s productivity.

Solutions—Equip your client service team with the answers to your customer’s queries and even build the answers offered to the customers on the web so that they will find the answers themselves whenever they have them.

Web-to-Case—if your customers can’t notice what they’re looking for on the web, you can have them log a case directly from your web site that straightaway enters Salesforce.com for agent resolution.

Additional functionality within the Service Cloud

If you have a a lot of complicated support needs or a lot of active client service team, you ought to considerService Cloud licenses.  Service Cloud licenses provides the quality Sales Cloud practicality for your users, and add extra practicality to higher equip your team to supply service a lot of expeditiously. you'll have Sales Cloud and service Cloud users within the same instance of Salesforce.com. extra features of Service Cloud include:

Agent Console—This helps your agents access relevant info about the client with fewer clicks. you'll style the console to maximise this efficiency.

Entitlement Management—if you've got Service Level Agreements that give completely different levels of support for your customers, you'll use entitlement management to make sure that you just deliver the right service level as well as 1st response and resolution times. you'll additionally incorporate automatic processes that give directions for reps on the most effective way to resolve cases.

Access to measure Agent web Chat (additional fee on top of Service Cloud license)—Incorporate live chat from the web to make sure that your clients get answers from you in real time without a phone call

Thanks
Amit Chaudhary

Saturday, 17 September 2016

Collection in salesforce | example using LIST and MAP | When to use Map Over List | When do we use set, map, list



While working on Developer forum i found lots of question for List ,Set and Map,  like below
1) When we should use Map over the list
2) When do we use set, Map,List
3) Bulkify code with Map
4) Using Maps and Sets in Bulk Triggers
5) Use of Map in Apex class.
6) Map over list to avoid query inside for loop

Solution :-

List, Set, Map are called collections in Apex:
List : A list is an ordered collection
1) so use list when you want to identify list element based on Index Number.
2) list can contain Duplicates

EX: List<Account> accList = new List<Account>();

Set : A set is an unordered collection
1) Do not contain any duplicate elements. So, use set if you want to make sure that your collection should not contain Duplicates.

EX: Set<Account> accSet = new Set<Account>()

 
Set<String> setString = new Set<String>();
// Add two strings to it
setString .add('item1');
setString .add('item2');

Map : A map is a collection of key-value pairs 
Each unique key maps to a single value. Keys can be any primitive data type, while values can be a primitive, sObject, collection type or an Apex object.

EX: Map<Id, Account> accMap = new Map<Id, Account>();

Map<Integer, String> mapOfString = new Map<Integer, String>();
mapOfString.put(1, 'Amit');               
mapOfString.put(2, 'Rahul');              
System.assert(mapOfString.containsKey(1)); 
String value = mapOfString.get(2); 
System.assertEquals('Rahul', value);
Set<Integer> s = mapOfString.keySet();



Map<String, String> myMap = new Map<String, String>{'a' => 'b', 'c' => 'd'};






Example 1:-  Using trigger populate the Account Field on the Contact record (only insert scenario)

If we use List and not Map

Apex Class

trigger ContactTriggerWithList on Contact (before insert) 
{
Set<Id> SetAccountId = new Set<Id>(); // Use set to collect unique account ID

for(Contact con: Trigger.new) 
{
 if(con.AccountId != null) 
 {
  SetAccountId.add(con.AccountId); // add Account in Set
 }
}

if( SetAccountId.size() >0 ) 
{
 List<Account> listAccount = [ Select Id, Name, Type from Account where Id IN :SetAccountId ]; // Query Related Account
 
 for(Contact con: Trigger.new) 
 {
  if(con.AccountId != null)
  {
   for(Account acc: listAccount)
   {
    if(con.AccountId == acc.Id)
    {
     con.Type__c = acc.Type;
    }
   }
  }
 }
} 
}

 
NOTE:- In this we are using List of Accounts, Where we have to loop through the matching Account every time to populate the Type__c in the second for loop. In this case need to use nested loop.

To Above the Nested Loop We can use the Map .

Same Trigger using the Map:

trigger ContactTriggerWithMap on Contact (before insert) 
{
    Set<Id> SetAccountId = new Set<Id>();
    for(Contact cont: Trigger.new) 
 {
        if(cont.AccountId != null) 
  {
            SetAccountId.add(cont.AccountId);
        }
    }
    
    if(SetAccountId.size() > 0 ) 
 {
        Map<Id, Account> mapAccount = new Map<Id, Account>([Select Id, Name, Type from Account where Id IN :SetAccountId ]);
        for(Contact cont: Trigger.new) 
  {
            if(cont.AccountId != null && mapAccount.containsKey(cont.AccountId) ) 
   {
                cont.Type__c = mapAccount.get(cont.AccountId).Type;
            }
        }
    }
}

NOTE:- Here we are using map of Account so we can directly use the Map to get the Account record. No need of 2nd for loop here



Related Link :-
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_bulk_idioms.htm
3) https://developer.salesforce.com/page/Apex_Code_Best_Practices


Thanks,
Amit Chaudhary