public class MapValueSort {
/** inner class to do soring of the map **/
private static class ValueComparer implements Comparator {
private Map _data = null;
public ValueComparer (Map data){
super();
_data = data;
}
public int compare(Object o1, Object o2) {
String e1 = (String) _data.get(o1);
String e2 = (String) _data.get(o2);
return e1.compareTo(e2);
}
}
public static void main(String[] args){
Map unsortedData = new HashMap();
unsortedData.put("2", "DEF");
unsortedData.put("1", "ABC");
unsortedData.put("4", "ZXY");
unsortedData.put("3", "BCD");
SortedMap sortedData = new TreeMap(new MapValueSort.ValueComparer(unsortedData));
printMap(unsortedData);
sortedData.putAll(unsortedData);
System.out.println();
printMap(sortedData);
}
private static void printMap(Map data) {
for (Iterator iter = data.keySet().iterator(); iter.hasNext();) {
String key = (String) iter.next();
System.out.println("Value/key:"+data.get(key)+"/"+key);
}
}
} This should output something of the lines of:
Value/key:BCD/3
Value/key:DEF/2
Value/key:ZXY/4
Value/key:ABC/1
Value/key:ABC/1
Value/key:BCD/3
Value/key:DEF/2
Value/key:ZXY/4
Where the bottom last four lines obviously is sorted on the map’s values and not it’s keys.
Ref: http://paaloliver.wordpress.com/2006/01/24/sorting-maps-in-java/ by paaloliver
2009年9月28日 星期一
Sorting maps in Java based on it’s values
訂閱:
張貼留言 (Atom)
網誌存檔
-
▼
2009
(42)
-
▼
9月
(13)
- Config the GuestOS's resolution in the VMware
- Sorting maps in Java based on it’s values
- jQuery Floating Layer Plugin
- C# 中的Map: Dictionary 的使用
- Barcode Image Generation Library
- Code 39 barcodes in C#
- An ASP.NET .ashx HTTP handler for Code 39 barcode ...
- http://www.codeproject.com/KB/aspnet/AspBarCodes.aspx
- Barcodes in ASP.NET applications
- Advanced Barcode Generation System for Code 39 Sta...
- jQuery Time Entry
- jQuery Timers
- Google Map Cursor
-
▼
9月
(13)
沒有留言:
張貼留言