📄 hashmapsorttest.java
字号:
package exec.day1003;
import java.util.*;
public class HashMapSortTest {
public static void main(String args[]){
HashMapSortTest t = new HashMapSortTest();
HashMap map = new HashMap();
map.put("001", new Integer(6500));
map.put("002", new Integer(3500));
map.put("003", new Integer(6500));
map.put("004", new Integer(2300));
t.sortHashMap(map);
}
/**
* 对HashMap排序,按照value降序排列,再按照key升序排列
* @param map
*/
public void sortHashMap(HashMap map){
//遍历HashMap,获取每一对key和value,并构建
//MapSortTest对象,添加到TreeSet中,实现排序
Set set = map.keySet();
TreeSet ts = new TreeSet();
for(Object key:set){
Object value = map.get(key);
MapSortTest t = new MapSortTest(key,value);
ts.add(t);
}
//输出排序后的结果
for(Object obj:ts){
System.out.println(obj);
}
}
class MapSortTest implements Comparable{
private Object key;
private Object value;
public MapSortTest(Object key,Object value){
this.key = key;
this.value = value;
}
public String toString(){
return key+": "+value;
}
public int compareTo(Object obj){
MapSortTest m = (MapSortTest)obj;
if(key instanceof String &&
value instanceof Integer){
int thisValue = ((Integer)this.value).intValue();
String thisKey = (String)this.key;
int mValue = ((Integer)m.value).intValue();
String mKey = (String)m.key;
if(thisValue==mValue){
return thisKey.compareTo(mKey);
}
return mValue-thisValue;
}
if(key instanceof String &&
value instanceof Double){
double thisValue = ((Double)this.value).doubleValue();
String thisKey = (String)this.key;
double mValue = ((Double)m.value).doubleValue();
String mKey = (String)m.key;
if(thisValue==mValue){
return thisKey.compareTo(mKey);
}
if(thisValue>mValue){
return -1;
}
return 1;
}
throw new RuntimeException("");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -