svz
svz

Reputation: 4588

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.

Upvotes: 13

Views: 28700

Answers (5)

RNJ
RNJ

Reputation: 15552

Why not try TreeSet. Does your list not allow duplicates? If so then the Set should be ok. As you are adding strings and this implements Comparator the set will be automatically sorted for you

If you had

Set<String> s = new TreeSet<String>();
s.add("B");
s.add("C");
s.add("A");

then the contents of the set would be A, B, C

Upvotes: 26

Santosh
Santosh

Reputation: 17893

A TreeMap should address your requirements. If your keys are not literals then use appropriate Comparator in TreeMap constructor.

Upvotes: 0

John Szakmeister
John Szakmeister

Reputation: 47032

Have you looked at TreeMap? It's based off of Red-Black trees which help maintain ordering, but still gives fast access.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533500

I would use a TreeSet which is a SortedSet. You need to define your custom class as Comparable based on the name and your collection will always be sorted.

Note: sorted collections have an O(log N) access time.

Upvotes: 1

Amit Deshpande
Amit Deshpande

Reputation: 19185

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.

Upvotes: 14

Related Questions