In my custom object I have two fields Name__c and QuestionString__c

I am trying to initialise a map with Name__c as key and QuestionString__c as value from a SOQL.

Map<String, String> ppmap = new Map<String, String>([SELECT Name__c, QuestionString__c FROM PObj__c]);

I tried the above but I get the error as

Invalid initializer type List found for Map: expected a Map with the same key and value types, or a valid SObject List

Can someone tell me if it is possible to initialize a map directly (without "Id") from SOQL ?

1 Answer 1


You can only use an initializer for a Map<Id, SObject>. If you want to map one field to another, you need a for loop.


Map<Id, SObject> data = new Map<Id, SObject>([
    SELECT ... FROM ... WHERE ...

Not Valid:

Map<String, String> data = new Map<String, String>([
    SELECT ... FROM ... WHERE ...


Map<String, String> data = new Map<String, String>();
for (MyObject__c record : [SELECT ... FROM ... WHERE ...])
    data.put(record.Field1__c, record.Field2__c);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .