I created a collection (list, set) for Decimal Values.

Following are the collection values and their corresponding debugs from debug log

I added values to collection and following is the debug. DEBUG 5:{51.00, 55.00, 66.66} //set values

I used for loop to iterate over the collection. BUt I see the following sequence in which they iterate.

 DEBUG 6:55.00
 DEBUG 6:51.00
 DEBUG 6:66.66

I expected it to be looping in the order of 51,55 and 66.66 at last. This behavior is same with list,set and map(looping over keyset).

  • Sets and maps are inherently unordered collections. You should never rely on order of iteration over them.
    – David Reed
    Feb 7, 2018 at 15:34

2 Answers 2


The iteration order of a Set is not defined (not part of its "contract") and depends on the underlying hash code generation and the specific implementation. (I'm a bit surprised that you say the toString method that the debug output uses produces a different order.)

Only Lists preserve order (this is part of their "contract") such as the order that the vales are added. But if for example you convert a Set to a List the ordering will have been lost and you will need to invoke the list's sort method to reset the ordering.

  • This answer is actually technically incorrect as of a few releases ago. While Set is still an unordered collection, the iteration order is now guaranteed to be the same for a given collection of values.
    – Adrian Larson
    Feb 8, 2018 at 17:19

Note from the documentation on Sets:

  • The iteration order of set elements is deterministic, so you can rely on the order being the same in each subsequent execution of the same code.

But in your first example, you are not iterating over the Set. You haven't even shared your debugging mechanism, but nowhere in the documentation does it say that debugging, serializing, or otherwise manipulating a Set wholesale will show the same order as iteration would.

You must log in to answer this question.

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