5

I have a list is specific order, Now from this list I want to create for example a Map<Id, Object>. Then Iterate through this map.

But the issue is when I do a map.get, as key is Set<> its unordered and it won't return in the order the map was created.

Is there a way to maintain the order in Map?

5
  • 5
    Use the list to iterate and grab value from map. List is ordered and since map created from it you have the list already right?
    – Eric
    Oct 16, 2017 at 15:44
  • You mean map.values() Oct 16, 2017 at 15:46
  • 3
    No. You said you created the map from a list. You have the ordered list. Use that to iterate and grab the mapped value on each iteration. Since using the list to iterate it will happen in the order of your list. Otherwise read releasenotes.docs.salesforce.com/en-us/summer15/release-notes/…
    – Eric
    Oct 16, 2017 at 15:48
  • Ok understood, you meant iterate using the original list and get the value from the map by doing map.get(list value). This way the value retrived will be in order. Oct 16, 2017 at 15:56
  • @Eric Great fix in summer 15, thanks for the hint :)
    – itsmebasti
    Oct 16, 2017 at 16:03

1 Answer 1

12

Use the list to iterate and grab value from map. List is ordered and since map created from it you have the list already right

You said you created the map from a list. You have the ordered list. Use that to iterate and grab the mapped value on each iteration. Since using the list to iterate it will happen in the order of your list. Otherwise read: Iteration Order for Maps and Sets Is Now Predictable

The order of elements in unordered collections (Map and Set) is now the same each time your code is run. Previously, the order of elements in unordered collections was arbitrary, and you couldn’t rely on the order of elements in maps and sets.

Ideally, you don’t want your code to depend on the order of elements in unordered collections. If you have such code, it could sometimes fail before this change. This change makes your code more robust because the iteration order in maps and sets is always the same.

This example illustrates how the iteration order is deterministic in a map. A map is created with two elements. Next, the for loop iterates over the map elements and writes the key and value of each element to the debug log. Each time you execute this snippet, the iteration order of the elements in the for loop is the same.

Map<String, String> currencyMap = new Map<String, String>();
currencyMap.put('France','Euro');
currencyMap.put('Japan', 'Yen');
// Iterate through the map elements.
for (String mapKey : currencyMap.keySet()) {
    System.debug('Key: ' + mapKey +
        ', Value: ' + currencyMap.get(mapKey));
}
// The output is:
Key: France, Value: Euro
Key: Japan, Value: Yen

You must log in to answer this question.

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