Suzan Cioc
Suzan Cioc

Reputation: 30107

Ordered generic Map implementation?

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?

Upvotes: 1

Views: 298

Answers (1)

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28005

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);

Upvotes: 4

Related Questions