I need my method to return two Maps. Is this possible?
Apex does not allow multiple return types. However, you can create a custom type to be returned from your method. It would have a Lead
and a Set<Date>
and a Set<String>
in it - allowing you to have strings and dates per Lead.
Similar to this:
public class LeadWrapperThing {
public Lead theLead { get; set; }
public Set<String> theStrings { get; set; }
public Set<Date> theDates { get; set; }
}
public List<LeadWrapperThing> getLeadWrapperThings() {
List<LeadWrapperThing> thingsList = new List<LeadWrapperThing>();
for (Lead someLead : listOfLeads) {
// create the wrapper
LeadWrapperThing lThing = new LeadWrapperThing();
// stick the lead in the wrapper
lThing.theLead = someLead;
// add stuff to the string set
lThing.theStrings = new Set<String>();
lThing.theStrings.add('a value');
// add stuff to the date set
lThing.theDates = new Set<Date>();
lThing.theDates.add(Date.today());
// add the wrapper object into the list to be returned
thingsList.add(lThing);
}
return thingsList;
}
or as an answer to your comment, if you want to use the lead as the key also and return a map
public Map<Lead, LeadWrapperThing> getLeadWrapperThingsMap() {
Map<Lead, LeadWrapperThing> thingsMap = new Map<Lead, LeadWrapperThing>();
for (Lead someLead : listOfLeads) {
// create the wrapper
LeadWrapperThing lThing = new LeadWrapperThing();
// stick the lead in the wrapper
lThing.theLead = someLead;
// add stuff to the string set
lThing.theStrings = new Set<String>();
lThing.theStrings.add('a value');
// add stuff to the date set
lThing.theDates = new Set<Date>();
lThing.theDates.add(Date.today());
// add the wrapper object into the Map to be returned, using the lead as the key
thingsMap.put(someLead, lThing);
}
return thingsMap;
}
// Usage:
// Map<Lead, LeadWrapperThing> wrappedLeadMap = yourClass.getLeadWrapperThingsMap();
// LeadWrapperThing wrappedThingForThisLead = wrappedLeadMap.get(theLead);
In addition to creating a new class to hold the values as Mark Pond suggested, you could take advantage of the fact that Maps
, like all collection types, are reference types rather than value types, and simply provide variables for the method to fill as parameters.
void fillLeadStringDates(Map<Lead, Set<String>> stringset, Map<Lead, Set<Date>> dateset)
{
stringset.put(aNewLead, 'a string');
dateset.put(aNewLead, Date.newInstance(0, 0, 0));
}