不能对Hashmap本身排序,而是用它构建一个list,对list排序!!!!!
package Test;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;
public class TestGod {
public static void main(String args[]){
HashMap<String, Integer> url= new HashMap<String,Integer>();
Random random=new Random(10);
for(int i=0;i<10;i++){
url.put("ob"+i,random.nextInt(100));
}
java.util.List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(url.entrySet());
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
// TODO Auto-generated method stub
if (o1.getValue() < o2.getValue())
return 1;
if (o1.getValue() == o2.getValue())
return 0;
else
return -1;
}
});
for(int i=0;i<list.size();i++){
Entry<String, Integer> entry=list.get(i);
System.out.println(entry.getKey()+","+entry.getValue());
}
}
}