Tigerware
Tigerware

Reputation: 3904

Change iteration order for a Map

How can I iterate over a Map in a specific desired order? I currently have a HashMap and want to be able to define a specific iteration order. The order should be able to get changed by the user.

My first thought was to use a LinkedHashMap since that one will give me an order of entries, but sadly the implementation only orders them by order of insertion or by order of access. Other than manipulating the insertion order with deletes, I dont see the LinkedHashMap fit for the task. Imo the implementation kind of falls short of what the docs say about it.

I also found the SortedMap, but that one uses a comparator, so I needs to evaluate that every time I want to iterate over the entries. This could be a solution, but is kind of expensive: O(n*log(n)).

So far Andreas comment seems to be the best solution, which is having both a HashMap and a ArrayList.

Upvotes: 0

Views: 258

Answers (3)

Hari Rao
Hari Rao

Reputation: 3240

If you want a key value pair and you want it to have properties of ArrayList then can you try

List<Pair<String, String>> ?

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

The correct answer for this question is you use incorrect data structure in cease you have to reorder it.

Upvotes: 0

Gawain
Gawain

Reputation: 1092

Convert the LinkedHashMap to an ArrayList and then switch the value. Then convert back to LinkedHashMap. O(n) for both space and time complexity.

Upvotes: 1

Related Questions