Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a Guava BiMap

Tags:

java

guava

I am new to the Guava library, but have found that the BiMap fits my needs nicely. My one issue is that I need to sort the values in my BiMap. Normally, I would have used a TreeMap due to its inherit sorting, but being able to invert the map to look at the keys as if they are values is a must.

So I was looking for advice from you experts about going about this. The solutions I see are: 1. Create a BiMap comparator and use my own map sorting utility. 2. Build my own 'BiTreeMap' data structure.

Is there a solution I haven't considered? Is there a 'Guava way' to do this that I missed? Thanks!

like image 764
Cody Avatar asked Nov 05 '12 17:11

Cody


1 Answers

We don't currently have a sorted BiMap type because it's a little ambiguous how it would work: would the entries be sorted by the keys? By the values? Would the forward entries be sorted by the keys, and the inverse entries be sorted by the values?

Currently, the only real available alternative is ImmutableBiMap, which retains the ordering that you put the entries in -- so ImmutableBiMap.copyOf(Maps.newTreeMap(map)) would give you a BiMap sorted by the keys.

(We might more seriously consider providing a directly sorted BiMap if you filed a feature request with more details on your use case, though.)

like image 54
Louis Wasserman Avatar answered Nov 05 '22 05:11

Louis Wasserman