Monday 29 February 2016

java - How to sort a map



I have a Map to sort as follows:



Map map = new HashMap(); 


It contains the following String keys:



String key = "key1.key2.key3.key4" 


It contains the following String values:



String value = "value1.value2"


where the key and value can vary by their number of dot sections from key1/value1 to key1.key2.key3.key4.key5/value1.value2.value3.value4.value5 non-homogeneously



I need to compare them according to the number of dots present in keys or in values according to the calling method type key / value :



sortMap(Map map, int byKey);


or



sortMap(Map map, int byValue);


The methods of course will return a sorted map.



Any help would be appreciated.


Answer



For starters, you will need to be using an instance of SortedMap. If the map doesn't implement that interface, then it has an undefined/arbitrary iteration order and you can't control it. (Generally this is the case, since a map is a way of associating values with keys; ordering is an auxiliary concern.)



So I'll assume you're using TreeMap, which is the canonical sorted map implementation. This sorts its keys according to a Comparator which you can supply in the constructor. So if you can write such a comparator that determines which is the "lower" of two arbitrary keys (spoiler alert: you can), this will be straightforward to implement.



This will, however, only work when sorting by key. I don't know if it makes much sense to sort a map by value, and I'm not aware of any straightforward way to do this. The best I can think of is to write a Comparator that sorts on values, call Map.getEntrySet and push all the entries into a list, then call Collections.sort on the list. It's not very elegant or efficient but it should get the job done if performance isn't your primary concern.



(Note also that if your keys aren't immutable, you will run into a lot of trouble, as they won't be resorted when externally changed.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...