+ Start a Discussion
Marcelo AgostinhoMarcelo Agostinho 

Sorting a Map

Hello, everybody!

 

Again, i'm here to do some questions...

 

I have the following code...

 

public Map<String,Double> calculaFaturamentoMensal(){

		Double soma; 
		
		Map<String,Double> faturamentoMensal = new Map <String,Double>();
		
		for(MovimentoMes__c movimento : 
                   [Select m.Valor__c, m.Mes_de_Referencia__c From MovimentoMes__c m]){
			if(faturamentoMensal.containsKey(movimento.Mes_de_Referencia__c)){
				soma = 0;
				soma = faturamentoMensal.get(movimento.Mes_de_Referencia__c);
				soma += movimento.Valor__c;
				faturamentoMensal.put(movimento.Mes_de_Referencia__c,soma);
			} else {				           
                                faturamentoMensal.put
                                (movimento.Mes_de_Referencia__c,movimento.Valor__c);
			}
			
		}
		
		return faturamentoMensal;
	
	}

 

After this, i want to sort my map by the key... trying to ensure that when I iterate over the map ill have the values based on the crescent sequence of the key...

 

Tks for all

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Cory CowgillCory Cowgill

1. Generate the Set of ID's from your map by calling futuramentoMensal.keySet();

2. Create a List from the Set.

3. Call futuramentoMensalKeyList.sort() to sort the the List of keys.

5. Iterate over the sorted list of keys, pulling the value from the map and doing whatever processing you need.

 

For more complex object sorting inside Apex code take a look at apex-lang on the AppExchange.

All Answers

Cory CowgillCory Cowgill

1. Generate the Set of ID's from your map by calling futuramentoMensal.keySet();

2. Create a List from the Set.

3. Call futuramentoMensalKeyList.sort() to sort the the List of keys.

5. Iterate over the sorted list of keys, pulling the value from the map and doing whatever processing you need.

 

For more complex object sorting inside Apex code take a look at apex-lang on the AppExchange.

This was selected as the best answer
Marcelo AgostinhoMarcelo Agostinho

Tks Cory... this worked perfectly for me. =)

skhalidskhalid

Thanks Cory, this worked great for me!

Kris KargonKris Kargon
Most of the students trust in est dissertation writing service. Because they provides the best service for the customers with fully satisfaction .The direct communication with the expert writers makes the students more comfort .This is the reason they buy dissertation online (https://uk.answers.yahoo.com/question/index?qid=20110415075430AAOeiDl)from these sites without any confusion.
 
Himanshu Rana 7Himanshu Rana 7
Map do not has  sorting support, they are a key value pair collection.
In apex to short a map we need to  use wrapper class and comparable interface
For more details go to :
http://himanshurana.in/http-himanshurana-in-sort-map-in-apex-