2

How can I get the index of a key in LinkedHashMap ?

for example I got this :

index key value 0 "a" 10 1 "b" 20 2 "c" 30 

Now I want to get the index of the key "b". What is in this case 1.

Any ways without a runtime of O(n) ? And I will use it in a loop so for example new ArrayList<String>(mapIndex.keySet()).indexOf(position_with_section_map[position]); wouldn't be a solution for me

1
  • Use it in a loop how? There's no API for using it at all, let alone in a loop. And the index values you've shown are only correct if the entries were inserted in that order. Commented Feb 11, 2016 at 22:06

2 Answers 2

2

No, there is no way to do this without a runtime of O(n) just from a LinkedHashMap. You could keep an extra Map<String, Integer> to keep the indices of the elements yourself, but that's really the only thing you can do.

Sign up to request clarification or add additional context in comments.

Comments

1

Adding to Louis Wasserman answer instead of creating a new map,you can move the index and value to a Pojo and save that as the value in the Map.

class Test{ int index; int value; public int getIndex(); public int getValue(); } 

Use the LinkedHashMap as LinkedHashMap String,Test>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.