问题
Got the solution.. Used linkedHashMap and was able to store the sorted key values in an array. Here's the link for the code.
Possible Duplicate:
store key values of sorted hashmap in string[]
I created a hashmap and then 'sorted by value' the elements in the map using this code. The code worked and i was able to display on screen the key value pairs sorted by value.
Now I want to store the keys(from the sorted elements) in a String[]. HashMap.keySet().toArray() doesn't help as the entired HashMap are not sorted.
Can anyone please suggest a method to do this?
further clarifying the situation - Suppose I have key value pairs like (a,1)(b,23)(c,7) by using the above link, i was able to get (a,1)(c,7)(b,23) as output. I want to store {a,c,b} as a string array. I hope the problem is clear now.
回答1:
Reusing this code you would just use
List keys = sortByValue(m);
String[] keyArray = keys.toArray(new String[keys.size()]);
Using generics would make this nicer. I would also sort by Map.Entry (from entrySet()) which would be faster and simpler.
回答2:
Sorting my keys is simple, use TreeMap.
TreepMap sortedMap = new TreeMap(someHashMap);
String[] sortedKeys = sortedMap.keySet().toArray();
回答3:
That code is not really sorting the HashMap - it is merely returning the keys, sorted by their value:
So all you need is:
Object[] key_array = sortByValue(m).toArray();
回答4:
I'd go either for something like
private static String[] keysSortedByValue(final Map<String, String> m) {
final String[] result = m.keySet().toArray(new String[m.size()]);
Arrays.sort(result, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
final String v1 = m.get(o1);
final String v2 = m.get(o2);
if (v1==v2) return 0;
if (v1==null) return -1;
if (v2==null) return +1;
return v1.compareTo(v2);
}
});
return result;
}
or use Map.Entry[] for greater efficiency (avoiding the lookup).
回答5:
I would use Google Collection:
Map<String, String> map = new HashMap<String, String>( );
map.put("ABC1", "VALUE1");
map.put("ABC7", "VALUE1");
map.put("ABC2", "VALUE2");
map.put("ABC3", "VALUE1");
Multimap multimap = TreeMultimap.create();
for(Map.Entry<String, String> entry: map.entrySet() ) {
multimap.put( entry.getValue(), entry.getKey() );
}
System.out.println( Arrays.toString( multimap.values().toArray() ));
来源:https://stackoverflow.com/questions/7415366/store-key-values-of-hashmap-in-string