[SalesForce] Salesforce creating field values as map keys and results as values

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]

    like 
    [
    id = Olist.id,
    name = Olist.name
    .....

    ]

Is it possible to make like that?

Best Answer

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": [
        "006d0000008WaWzAAK",
        "006d0000008WaWpAAK",
        "006d0000008WaXHAA0"
    ],
    "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
        field2values.get(key).add(oppMap.get(key));
    }

}

System.debug(Json.serializePretty(field2values));
Related Topic