The standard library LinkedHashSet
is a HashSet
that provides insertion-order iteration. Is there a version of Guava's BiMap
that maintains insertion-order iteration on keys and values? I do need the BiMap
to be mutable, so ImmutableBiMap
is not sufficient for my purpose.
Asked
Active
Viewed 987 times
3

Jake Cobb
- 1,811
- 14
- 27
-
2Uhm, what should define the insertion order? I take it the keys should? – fge Dec 12 '14 at 21:29
-
I would accept key ordering, but keys and values are put in together and an exception is thrown if you try to put in an existing value under a different key, so I think there is no practical difference. – Jake Cobb Dec 12 '14 at 22:15
-
you could just implement guava's bimap interface yourself using two linked hashmaps. Probably not too hard to do. – Jilles van Gurp Dec 19 '14 at 16:03
2 Answers
3
The only available implementation is ImmutableBiMap<K,V>
. You can check the implementations here.
You can use a LinkedHashMap
and convert it to with copyOf(Map<? extends K,? extends V> map)
to make it an ImmutableBiMap<K,V>
. Will it work for you?

Jake Cobb
- 1,811
- 14
- 27

Sezin Karli
- 2,517
- 19
- 24
-
1Thanks, but it doesn't help. I want a BiMap for ease of use, but it needs to be mutable. If I maintain a different collection type (or types, e.g. two maps) then I don't need a BiMap at all. – Jake Cobb Dec 12 '14 at 22:18
-
-2
You could get the keyset, convert it to an array and then loop over the array like this:
Object[] keys = someBiMap.keySet().toArray();
for(Object key : keys) {
Object entry = someBiMap.get(key);
}
This is not a very nice solution but it's the only solution that I have found for this problem

Equator
- 1
- 2
-
1`keySet` returns a `Set`, so it doesn't guarantee insertion order. With `HashBiMap` they are almost never in insertion order. – Jake Cobb Aug 13 '18 at 13:41