java sort hashtable with object value by the objecs string parameter
I have an hashable that contains a string key , and a class object value:
Hashtable<String,myclass>m_class_table = new Hashtable<String开发者_运维问答,myclass>();
inside 'myclass' I have a String field value,
I need to sort my hashtable according to this string value.
I can't just sort it by the hashtable values beacuse it is an object..
How can this be done?
Thank's In Advance.
I need to sort my hashtable according to this string value.
A hashtable is not a sorted data structure.
You can use some SortedMap
, such as a TreeMap
but those data structures sorts on the keys, so that will only work if the key equals the string-field of the object pointed to.
I can't just sort it by the hashtable values beacuse it is an object..
You need to provide a Comparator<myclass>
, or, let myclass
implement the Comparable
interface.
Depending on how you iterate over the hash-table, you could perhaps do like this:
List<myclass> myObjects = new ArrayList<myclass>(m_class_table.values());
Collections.sort(myObjects, new Comparator<myclass>() {
@Override
public int compare(myclass o1, myclass o2) {
o1.stringField.compareTo(o2.stringField);
}
});
and then iterate over the myObjects
list. (Elements in a List
are ordered.)
A slight variation on aioobe's answer: I'd create a List of the Map entries and sort that list. That way you still have access to the complete map entries.
Map<String, MyClass> map = new HashMap<String, MyClass>();
// add some entries
List<Entry<String,MyClass>> entryList =
new ArrayList<Entry<String,MyClass>>(map.entrySet());
Collections.sort(entryList, new Comparator<Entry<String,MyClass>>() {
public int compare(
Entry<String, MyClass> first, Entry<String, MyClass> second) {
return first.getValue().getFoo()
.compareTo(second.getValue().getFoo());
}
});
精彩评论