Home Sets and maps

Sets, maps, and ordering

When working with sets, recall that the Set interface does not guarantee the items will be ordered in any particular way. That means that if you are trying to get an item at a certain "index" or get the "first" item in a set (whether it's a TreeSet or a HashMap, you are doing something wrong and should restructure your code.

The same kind of logic also applies for keys in maps.

Random access with sets

Similarly, there is no clean way in Java to obtain some arbitrary element within a set, or an arbitrary key within a map. If you encounter a case where it would be useful to do so, you should restructure your code so this case no longer comes up.