How do i parse a map (foreach) in the same order i created it (JAVA)

Check out LinkedHashMap for a Map implementation with predictable iteration order. You also might consider just using a List if you're not actually doing lookup by keys.


Let's see. Your requirements seem to be:

  1. You have a set of key / value pairs, where the keys are unique.
  2. You want to be able to do fast lookup of the value for a given key.
  3. You want to be able to iterate over the keys (or pairs) in insertion order.
  4. You want to be able to iterate over the values in order of some field of the value type.

There is no single standard Java collection class that satisfies all of these requirements. And I don't think that Commons collections or Google collections would either ...

If you were to throw out requirement 3, then a TreeSet (instantiated with a custom Comparator) would do the job. If you were to throw out requirement 4, then a LinkedHashMap would do the job.

To satisfy all requirements you need to do one of the following:

  • Use a LinkedHashMap, and when you want to iterate in some order dependent on the values extract the map's values collection, sort it using your custom comparator, and return an iterator for the sorted collection.

  • Use both a LinkedHashMap and a TreeMap, and update the two in parallel.

  • Create a custom fascade class for a LinkedHashMap and a TreeMap. This needs to keep both data structures up to date when you call put, remove etcetera, and also provide extra methods for getting the sorted values.