1

I am trying to do this:

Map<Id,Id> reqMap = new Map<Id,Id>();
reqMap = [Select Id, TeamId from SObject];

Id and team Id are both of type Id. I don't want the entire SObject, just those two fields. I would like my map to look like:

{Id = xyz, TeamId =abc}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Riz
  • 91
  • 1
  • 6

1 Answers1

0

Your question is bit unclear. {Id = xyz, TeamId =abc} is not a Map<Id,Id>. Your keys are strings (fieldnames), not Ids.

If you need generic way to access all fields as key => value - you can already do it with sObject class get methods. Or use getPopulatedFieldsAsMap. Read up about sObject class (common base for all Account, Contact, Opportunity, MyCustomObject__c...).

Contact c = [SELECT Id, AccountId, LastName, Email FROM Contact LIMIT 1];

System.debug(c.AccountId); // "normal" access

System.debug(c.get('AccountId')); // map-like access
System.debug(c.get('Email'));

// or loop through them all
Map<String, Object> myMap = c.getPopulatedFieldsAsMap();
for(String key : myMap.keyset()){
    System.debug(key + ' -> ' + myMap.get(key));
}

If you really need a Map<Id, Id> where key is Id and value is TeamId...

Typically you can put whole objects into the map (simple, quick, 1-liner operation without a loop; and you never know if you won't need more fields accessed by that Id so why not)

Map<Id, Contact> contacts = new Map<Id, Contact>([SELECT Id, AccountId FROM Contact LIMIT 10]);
for(Id i : contacts.keyset()){
    System.debug(i + ' -> ' + contacts.get(i).AccountId);
}

Or really make it Map<Id, Id> but then you need to loop over them:

Map<Id, Id> contactToAccount = new Map<Id, Id>();
for(Contact c: [SELECT Id, AccountId FROM Contact LIMIT 10]){
    contactToAccount.put(c.Id, c.AccountId);
}
System.debug(contactToAccount);
eyescream
  • 18,088
  • 2
  • 34
  • 46