0

I am trying to learn about the maps and for this I am trying to do an exercise. For I have the Order and Opportunity objects, the Order object has an Opportunity__c field that relates to Opportunity.

I receive a list of services in one method. I am trying to make a map of type where the Id is the Id of an Order.

I am trying to fill in the map using a for loop but I am not able to add the Order Id and the Opportunity at the same time.

At first I made a double for loop and so I get the method to work correctly, but I understand that it is not a good way to act using double loops.

I show you the code I have so far:

public static void metodo1 (List<Order> listaOrders){

        Set<Id> idsOpps = new Set<Id>();
        Map<Id, Order> mapOrders = new Map<Id, Order>();
        Map<Id, Opportunity> mapOpps = new Map<Id, Opportunity>();
        List<Opportunity> listaOppsParaActualizar = new List<Opportunity>();

        for(Order item : listaOrders){
            mapOrders.put(item.Id, item);
            idsOpps.add(item.Oportunidad__c);
        }

        for(Opportunity opp : [SELECT ID, Name FROM Opportunity WHERE Id IN : idsOpps]){
            mapOpps.put(opp.Id, opp);    
        }

        for(Order item : listaOrders){
            mapOpps.get(item.Oportunidad__c).Total_servicios__c -= item.TotalAmount;
            listaOppsParaActualizar.add(mapOpps.get(item.Oportunidad__c));
        }

        if(!listaOppsParaActualizar.isEmpty()){
            update listaOppsParaActualizar;
        }
    }

I am not sure that this is a correct way to do it because I use a Set, a list and two maps and I think it is an not optimal way of working.

Does anyone have an idea of how I could do this? Thank you very much for any help, comment ...

Greetings.

1
  • 1
    Welcome to SFSE. Please edit your post to show us the code you've tried so far and share where you're stuck or the specific error you're confronting.
    – David Reed
    Feb 12, 2020 at 13:42

1 Answer 1

3

You can simply get the maps from the respective lists without looping.

Map<Id, Order> mapOrders = new Map<Id, Order>(listaOrders);
Map<Id, Opportunity> mapOpps = new Map<Id, Opportunity>([SELECT ID, Name FROM Opportunity WHERE Id IN : idsOpps]);

You must log in to answer this question.

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