Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i keep a hashset alphabetically ordered?

I have a collection of a big number of objects that are defined by name/value pairs. I need to have fast access to any of their values and to be able to return them ordered alphabetically by name. First I thought I might use a HashMap to get fast access. But it gave me no ordering. I decided to switch to LinkedHashSet.
The problem with it is that I need to be able to insert new Objects in the right places of the list, but LinkedHashSet doesn't allow that. I also need to be able to access Objects by their index as well as by name.

Will be thankful for any ideas.

like image 978
svz Avatar asked Sep 07 '12 08:09

svz


People also ask

How do I sort HashSet alphabetically?

It means that HashSet does not maintains the order of its elements. Hence sorting of HashSet is not possible.

Can HashSet be ordered?

HashSet does not maintain any order while LinkedHashSet maintains insertion order of elements much like List interface and TreeSet maintains sorting order or elements.


1 Answers

You can use TreeMap

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

like image 77
Amit Deshpande Avatar answered Sep 27 '22 23:09

Amit Deshpande