Search code examples
javadictionarysortingforeach

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


So i have a map that i created (inserted data) in an order i wanted. When parsing the map the 1st key returned in foreach is not the first key i inserted. Is there a way for that to happen?

Also sorting my map is kinda tricky cause it has to be sorted by Value and in specific field within the Value. Ty


Solution

  • 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.