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
Let's see. Your requirements seem to be:
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.