In Java: Get array of values of a map sorted by the map's keys
I have a hashmap, I wish to get an array of the values in this hashmap, but I wish for the array to be sorted by the keys in the hashmap.
For instance if the map looks like this:
- <2,obj1>
- <4,obj2>
- <0,obj3>
- <10,obj4开发者_开发技巧>
- <5,obj5>
- <1,obj6>
- <15,obj7>
- <3,obj8>
I want the array to be: [obj3,obj6,obj1,obj8,obj2,obj5,obj4,obj7]
The faster the better. Is there a built in way to do this?
Sounds like you want a SortedMap
, specifically a TreeMap
. You can use the fact that the map maintains a sorted list of keys to generate your output array, e.g. by using SortedMap.values()
or by iterating over the entries in the map.
I always like when I can answer in the form of a passing unit test:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
public class SortedMapValuesTest extends TestCase {
public void testSortedMapValues() throws Exception {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 200);
map.put(2, 300);
map.put(3, 100);
List<Integer> list = getSortedMapValues(map);
assertEquals("[200, 300, 100]", list.toString());
}
private <K extends Comparable<K>, V> List<V> getSortedMapValues(Map<K, V> map) {
ArrayList<K> keys = new ArrayList<K>(map.keySet());
ArrayList<V> values = new ArrayList<V>(keys.size());
Collections.sort(keys);
for (K key : keys)
values.add(map.get(key));
return values;
}
}
精彩评论