2008年3月26日 星期三

[JAVA] Sorting HashMap base on Value

Answer:
Example:
you could subclass HashMap and provide a new method 'iterator()' that returns an Iterator that will iterate over the elements in the order you require:

Code 1.

class SortedHashMap extends HashMap {
public Iterator iterator() {
Collection collection = this.values();
Object[] array = collection.toArray();
Arrays.sort(array);
return Arrays.asList(array).iterator();
}
}

Code2:

SortedHashMap map = new SortedHashMap();

map.put("111", "Fred");
map.put("222", "Bill");
map.put("333", "Harry");
map.put("444", "Alan");
map.put("555", "Dave");
map.put("666", "Jim");

System.out.println("Sort by value (name):");

Iterator iter = map.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}

System.out.println("\nRetrieve value (name) by index:");

System.out.println("444 = " + map.get("444"));
System.out.println("222 = " + map.get("222"));
System.out.println("111 = " + map.get("111"));
System.out.println("555 = " + map.get("555"));
System.out.println("333 = " + map.get("333"));
System.out.println("666 = " + map.get("666"));

/* Output :
Sort by value (name):
Alan
Bill
Dave
Fred
Harry
Jim

Retrieve value (name) by index:
444 = Alan
222 = Bill
111 = Fred
555 = Dave
333 = Harry
666 = Jim
*/Any programming problem can be solved

沒有留言: