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.

- 4,516
- 11
- 40
- 66
5 Answers
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

- 15,272
- 18
- 86
- 131
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.

- 19,001
- 4
- 46
- 72
-
1This is the wrong answer. A TreeMap does not guarantee singularity like the Set does. Use a TreeSet instead – checklist Apr 27 '16 at 11:02
-
1Note: duplicate objects are not allowed in TreeSet but allowed in TreeMap. – Yuci Apr 29 '16 at 11:24
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.

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

- 44,691
- 9
- 89
- 79
A TreeMap
should address your requirements. If your keys are not literals then use appropriate Comparator
in TreeMap constructor.

- 17,667
- 4
- 54
- 79