Sortable HashMap-like data structure in Java?

纵饮孤独 提交于 2019-12-04 15:48:30

问题


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



来源:https://stackoverflow.com/questions/5113688/sortable-hashmap-like-data-structure-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!