Sortable HashMap-like data structure in Java?

2019-03-22 06:37发布

问题:

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?

回答1:

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!



回答2:

SortedMap sorted only by keys