Converting List to map

I have a query that

List OList = [select id,name,fld3,fld4,fld5 from Opportunity]

i need to add field name like 'id,name,fld3,fld4 etc,.. as map keys and results of the fields as map values

List<Opportunity> OList = [select id,name from Opportunity]

    id = Olist.id,
    name = Olist.name


Is it possible to make like that?

2 Answers 2


Have I understood your question correctly?

1: i need to add field name like 'id,name,fld3,fld4 etc,.. as map keys

String fieldNames = String.join(new List<String>{
    SObjectType.Opportunity.Fields.Id.Name, //"Id"
    SObjectType.Opportunity.Fields.Name.Name //"Name"
}, ',');

List<Opportunity> opportunities = Database.query('SELECT ' + fieldNames + ' FROM Opportunity');

2: and results of the fields as map values

You are looking for data structure like this?

    "Id": [
    "Name": [
        "Pyramid Emergency Generators",
        "Dickenson Mobile Generators",
        "Grand Hotels Emergency Generators"

You can use a Map<String,List<Object>> data structure to hold all the field values. Then convert the SObject into a Map itself to loop over its fields easily. Here's a code sample that yields the above:

//select any fields you want
List<Opportunity> opportunities = [SELECT Id, Name FROM Opportunity]; //or from above

//prepare the data structure to hold the list of values
Map<String,List<Object>> field2values = new Map<String,List<Object>>();

//every opportunity
for (Opportunity opportunity : opportunities) {
    //we can convert any SObject into a Map
    Map<String,Object> mapOpp = (Map<String,Object>)Json.deserializeUntyped(Json.serialize(opportunity));

    //every field
    for (String key : mapOpp.keySet()) {

        //leave out the metadata
        if (key == 'attributes') continue;

        //list of values needs to be initialized the first time around
        if (field2values.get(key) == null) field2values.put(key, new List<Object>());

        //populate each value



You can use the dynamic DML syntax to retrieve fields from an sobject based on another variable. For example:

List<Opportunity> myList=[select id, Name from opportunity];

String keyField='id';
String valField='Name';

Map<Id, String> oppsMap=new Map<Id, String>();

for (Opportunity opp : myList)
  oppsMap.put( (Id) opp.get(keyField), (String) opp.get(valField) );

You must log in to answer this question.

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