1

Which library is the best with ordered map implementation?

Implementation is required to be

1) generic

2) accessible by integer index

One from JRE can't be accessed by index: http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html

One from Commons-Collections 3.2 is not generic: http://commons.apache.org/proper/commons-collections//javadocs/api-release/org/apache/commons/collections/map/LinkedMap.html

One from Commons-Collection 4.0 is not released yet.

And can't find appropriate class in Guava. Is there one?

Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385
  • ordered as in insertion order? natural order? custom order? – assylias Mar 19 '13 at 15:57
  • Do you realize that any linked map will give you O(N) performance for retrieval by index? You can get identical performance by simply walking the iterator. – parsifal Mar 19 '13 at 16:17
  • If you describe the actual problem that you're trying to solve, you might find that there's a better solution. – parsifal Mar 19 '13 at 16:18
  • @parsifal I disagree with O(N). Isn't it possible to have two parallel structures in implementation? – Suzan Cioc Mar 19 '13 at 16:49
  • @Suzan - so what data structure do you propose? – parsifal Mar 19 '13 at 16:52
  • It's fine to disagree, but at least you should understand the data structures. If you want list semantics, you have two options: linked or array-backed. A linked list always costs O(N) for indexed retrieval; there's no way around that. An array-backed list gives you O(1) indexed retrieval, but if you delete items from the map you'll need to pay O(N) to update the array. – parsifal Mar 19 '13 at 16:54

1 Answers1

4

It can be done with ImmutableSortedMap (it's immutable and null hostile):

// use ImmutableSortedMap#copyOf or one of builders - naturalOrder or orderedBy
ImmutableSortedMap<K, V> map = ImmutableSortedMap.copyOf(origMap, comparator);
map.keySet().asList().get(index);

But what problem are you trying to solve? Seems to me like bad code smell...

EDIT:

If you want insertion order instead of using comparator, just use ImmutableMap:

ImmutableMap.copyOf(origMap).keySet().asList().get(index);
Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112