2

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?

2 Answers 2

4

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 Map in Java that stores its elements in sorted order, consider looking into TreeMap, 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 two TreeMaps, though, one from keys to values and one from values to keys.

Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

I doesn't think BiMap supports sorted keys or values
@Pangea- I didn't know that; thanks for pointing this out. I've updated my answer accordingly.
4

SortedMap sorted only by keys

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.