I have a LinkedHashMap (called info) that contains name/age (string/int) pairs. How can I get the position of the key/value if I input the key? For example, if my LinkedHashMap looked like this {bob=12, jeremy=42, carly=21} and I was to search jeremy, it should return 1 as its in position 1. I was hoping I can use something like info.getIndex("jeremy").
I have a LinkedHashMap (called info) that contains name/age (string/int) pairs. How can I
Share
HashMapimplementations in general are un-ordered forIteration.LinkedHashMapis predictablely ordered forIteration( insertion order ) but does not expose theListinterface and aLinkedList( which is what mirrors the key set insertion order ) does not track index position itself either, it is very in-efficient to find the index as well. TheLinkedHashMapdoesn’t expose the reference to the internalLinkedListeither.The
KeySetthat contains the keys does not guarantee order as well because of the hashing algorithms used for placement in the backing data structure of the inheritedHashMap. So you can’t use that.The only way to do this, without writing your own implementation, is to walk the
Iteratorwhich uses the mirroringLinkedListand keep a count where you are, this will be very in-efficient with large data sets.Solution
What it sounds like you want is original insertion order index positions, you would have to mirror the keys in the
KeySetin something like anArrayList, keep it in sync with updates to theHashMapand use it for finding position. Creating a sub-class ofHashMap, sayIndexedHashMapand adding thisArrayListinternally and adding a.getKeyIndex(<K> key)that delegates to the internalArrayList.indexOf()is probably the best way to go about this.This is what
LinkedHashMapdoes but with aLinkedListmirroring theKeySetinstead of anArrayList.