TreeMap默认按照Key排序,我现在想按照Value排序,用Comparator实现,怎么写?求助大神

要实例,主要是TreeMap调用Comparator的那条语句,谢谢
2024-12-15 09:33:37
推荐回答(2个)
回答1:

final Map map = new HashMap();
map.put("语文课本",11);
map.put("英语课本",9);
map.put("数学课本",20);
map.put("政治课本",12);
map.put("化学课本",12);
System.out.println(map.toString());
//结果为{政治课本=12,英语课本=9,数学课本=20,语文课本=11,化学课本=12}
Map orderByValue=new TreeMap(
    new Comparator(){
        public int compare(String obj1,String obj2){
            if(map.get(obj1)!=map.get(obj2)){
                return map.get(obj2).compareTo(map.get(obj1));
            }else{
                return map.get(obj1);
            }
        }
    }
);
orderByValue.putAll(map);
System.out.println(orderByValue.toString());
//结果为{数学课本=20,政治课本=12,化学课本=12,语文课本=11,英语课本=9}

回答2:

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;

public class SortMapByValue {
public static void main(String[] args){
TreeMap newMap=new TreeMap();
newMap.put("dsaf1", 1);
newMap.put("dsaf9", 9);
newMap.put("dsaf4", 4);
newMap.put("dsaf7", 7);
newMap.put("dsaf6", 6);
newMap.put("dsaf3", 3);
newMap.put("dsaf10", 10);

ByValueComparator bvc =new ByValueComparator(newMap);
List newList=new ArrayList(newMap.keySet());
Collections.sort(newList, bvc);
for(String str:newList){
System.out.println(str+"================================="+newMap.get(str));
}

}

/**
* @description
* 对HashMap按值进行排序
*
* */
static class ByValueComparator implements Comparator {

TreeMap base_map;

public ByValueComparator(TreeMap base_map) {

this.base_map = base_map;

}

public int compare(String arg0, String arg1) {

if (!base_map.containsKey(arg0) || !base_map.containsKey(arg1)) {

return 0;

}

if (base_map.get(arg0) < base_map.get(arg1)) {

return 1;

} else if (base_map.get(arg0) == base_map.get(arg1)) {

return 0;

} else {

return -1;

}

}

}

}
这样行吗 你看看