1

To add Ids to a Set without looping over a list of SObjects I tried to do the following. In every org I tried it leads to this error:

Set<Opportunity> myset = new Set<Opportunity>([SELECT Id FROM Opportunity]);
Map<Id, Opportunity> mymap = new Map<Id, Opportunity>(mySet);
System.debug(mymap.keySet());

when I try to save. When I just change

Set<Opportunity> myset = new Set<Opportunity>([SELECT Id FROM Opportunity]);
Map<Id, Opportunity> mymap = new Map<Id, Opportunity>(new List<Opportunity>(mySet));
System.debug(mymap.keySet());

it works. Why?!

  • 1
    What are you trying to accomplish by doing this? Why do you create an Opportunity Set, and then creating a Map from that? Why don't you directly do Map<Id, Opportunity> mymap = new Map<Id, Opportunity>([SELECT Id FROM Opportunity]); – pjcarly Mar 21 '13 at 12:36
  • This is a stripped down version of my code. In the actual class there is just a set and not SOQL. Anyway this should generally work and my question is not so much "does this code fragment" make sense but "why does it fail so miserably?" ;) – Robert Sösemann Mar 21 '13 at 14:33
  • 2
    There's probably a "here be dragons" label on the Apex compiler. I can't find it now but there was a crazy question about thing similar to Map<Decimal, List<Set<Map<Id, Integer.class>>>> and it was compiling ok... – eyescream Mar 21 '13 at 14:58
2

http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_collections_maps_from_SObjects.htm

Map<Id, sObject> can be initialized with a List<sObject> or a [query].

Or - without the () - with {comma, separated, list, of, items, in, curly braces}.

There's no method to initialize it with a set. Similarly putAll method accepts a compatible map or a list, but not a set. Why did you think you can use a set?

Just Use PJC's suggested code :)

Map<Id, Opportunity> mymap = new Map<Id, Opportunity>([SELECT Id FROM Opportunity]);
Set<Id> mySet = mymap.keyset();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.