Burt R.
Burt R.

Reputation: 31

Re-order Map based on ordering of List

Lets say I have two data structures, an ordered List of Strings and a HashMap. The List looks like:

types = ["string", "integer", "boolean", "integer"];

And the HashMap, with an object key and a String value, that looks like:

map = {2=integer, true=boolean, 7=integer, "dog"=string};

Whats the easiest/most efficient way to reorganize the "order" of the Map so that the Map's values align with the ordering of the list, i.e., the Map would now look like this when printed:

map = {"dog"=string, 2=integer, true=boolean, 7=integer};

Upvotes: 3

Views: 943

Answers (2)

mettleap
mettleap

Reputation: 1410

Build a reverse hashmap like so,

types = ["string", "integer", "boolean", "integer"];

map = {2=integer, true=boolean, 7=integer, "dog"=string};

reversedmap = {integer=[2,7], boolean=true, string=dog};

then iterate through the list and the get the corresponding keys from the reversedmap.

for example, first you get "string" from types -> so you know the corresponding key should be "dog". Insert this key-value pair in some other map (of type LinkedHashMap). Keep on doing this till you reach the end of types list.

EDIT: Thank you @FedericoPeraltaSchaffner for pointing this out.

If you get two values from the reversedmap (for eg, in case of "integer" element), you can choose one of them (doesn't matter which) to be inserted in the LinkedHashMap while also subsequently removing it from the reversedmap. And then you procced to the next element in the types list

Upvotes: 1

Geoffrey Wiseman
Geoffrey Wiseman

Reputation: 5637

HashMap does not offer an order guarantee. From the documentation:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

So if you wanted an ordered Map you'd normally want to start with an implementation of SortedMap (documentation).

Unfortunately, SortedMap sorts by key, and you want to sort by value, so you're either going to have to look at third-party collection libraries or consider something like LinkedHashMap (documentation), which has a predictable iteration order, even if it doesn't maintain a sort.

What strategy would you be using to decide which integer to use when there's two as your example shows?

Upvotes: 3

Related Questions