Is there some sort of data structure in Java that resembles a HashMap that can be sorted by key or value? In PHP you can have associative arrays that are sortable. Is there such a thing in Java?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
HashMaps are unsorted almost by definition; a good hash function will produce a seemingly random distribution of the keys.If you want to use a
Mapin Java that stores its elements in sorted order, consider looking intoTreeMap, which is backed by a sorted binary search tree.If you want something that can be sorted either by key or by value, you may be looking for a bidirectional map or “bimap.” Java doesn’t have on in its standard libraries, and the closest implementation I know of is Google’s
BiMap. However, as Pangea pointed out, it does not support elements in sorted order. You could easily make your own implementation by just using twoTreeMaps, though, one from keys to values and one from values to keys.Hope this helps!