Sorting a HashTable by the values (including alphanumeric)
I have a HashTable
with alphanumeric values. 开发者_如何学编程I want to sort them.
HashTable
doesn't preserve the order.
So better Create a List
out of it and Sort it.
You need to wrap your types into a class and then implement a Comparator that compares all the types of values (in your term),
class Foo implements Comparator<Foo>{
private int no;
private String alpha;
//+getter/setters
public int compare(Foo f1, Foo f2){
//put your logic here
}
}
Why? You presumably chose HashTable over TreeMap because it had better performance (and no ordering). If you don't want the performance and you do want the ordering, use a TreeMap.
If you don't want to create a new class to hold the key/value relationship and it you are not interested in a TreeMap, then something like the following will also work:
ArrayList<Entry<String,String>> list = new ArrayList<Entry<String,String>>();
list.addAll(map.entrySet());
Collections.sort(list, new Comparator<Entry<String,String>>() {
@Override
public int compare(Entry<String, String> o1, Entry<String, String> o2) {
//your logic here;
}
});
First question - do you really mean sort the values, or do you mean sort the keys?
If you only want to access the sorted values in order once the best way is create a list or array then sort.
For values: Arrays.sort(table.values().toArray())
or Collections.sort(new ArrayList(table.values()))
For keys: Arrays.sort(table.keySet().toArray())
or Collections.sort(new ArrayList(table.keySet()))
For more on these sorting methods: Arrays.sort() or Collections.sort().
If you want to repeatedly use based on sorted keys, you would be better using a TreeMap.
If you repeatedly want to access based on sorted values (rather than keys), then you could always insert in order into a LinkedHashMap, which will keep the ordering.
精彩评论