Arpssss
Arpssss

Reputation: 3858

Hash Multi-Map Issues

I have two questions on Java HashMap:

1) Is it possible in any implementation of Java HashMap to get corresponding Key from the value ? I am using HashMultiMap (key -) Multiple values).

2) Is it possible in any implementation of Java HashMap to get Key position in the HashMap ? If so, then If I add new key, is it possible that the key position is changed ? I am using HashMultiMap (key -) Multiple values).

If both of them answer is NOT, how is it possible to implement manually (any idea ?) ?

Upvotes: 1

Views: 476

Answers (1)

Jesper
Jesper

Reputation: 206876

1) Yes, but not in an efficient way, and there are no methods in interface Map to do this with one method call. You'd have to iterate over the entries of the map until you find one with the value you're looking for; then you have the key of the corresponding entry. There are implementation such as Google Guava's BiMap that do let you do reverse lookups efficiently.

2) No, because a map is not an ordered collection: keys do not have a defined position in a map. If you need this, you could use for example LinkedHashMap, which keeps key-value pairs in the order they are inserted in the map.

Upvotes: 6

Related Questions