对TreeMap条目进行排序

时间:2016-03-17 14:55:06

标签: java collections comparator

我有一个TreeMap和一个按键Comperator工作:

Map<String, Long> movieReviewsTreeMap = new TreeMap<String, Long>(new MyComperator());

class MyComperator implements Comparator<String>{
@Override
public int compare(String s1, String s2) {
                return s1.compareTo(s2);
            }
        }

我试图修改比较器以比较TreeMap条目。 我的目标是按值(从最高到最低)对TreeMap进行排序,如果两个值相等,则按键进行排序。

感谢。

2 个答案:

答案 0 :(得分:0)

您只能对java.util.TreeMap中的键进行排序,但您可以扩展它并覆盖使用比较器来实现某些附加逻辑的方法。

答案 1 :(得分:0)

您可以尝试一些同样的东西,以满足您的要求..

import java.util.*;
import java.util.Map.Entry; 

public  class TestCollection13{

    public static void main(String args[]){

        Map<MyComperator, Long> movieReviewsTreeMap = new TreeMap<MyComperator, Long>(new MyComperator());

        Long l1 = new Long(5);
        movieReviewsTreeMap.put(new MyComperator("a", l1),l1);

        Long l2 = new Long(2);
        movieReviewsTreeMap.put(new MyComperator("a", l2),l2);

        Long l3 = new Long(6);
        movieReviewsTreeMap.put(new MyComperator("a", l3),l3);

        Long l4 = new Long(0);
        movieReviewsTreeMap.put(new MyComperator("a", l4),l4);

        for(Entry<MyComperator, Long> entry : movieReviewsTreeMap.entrySet()){
            System.out.println("Key : " + entry.getKey().getKey() +  " , value :" + entry.getValue());
        }

    } 
}


class MyComperator implements Comparator<MyComperator>{

    String key;
    Long value;

    MyComperator(){

    }

    MyComperator(String key, Long value){
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Long getValue() {
        return value;
    }

    public void setValue(Long value) {
        this.value = value;
    }

    @Override
    public int hashCode() {
        return this.key.length();
    }

    @Override
    public boolean equals(Object obj) {

        MyComperator mc = (MyComperator)obj;

        if(mc.getKey().equals(this.getKey())  && mc.getValue().equals(this.getValue())){
            return false;
        }

        // TODO Auto-generated method stub
        return super.equals(obj);
    }

    @Override
    public int compare(MyComperator o1, MyComperator o2) {

        if(o1.getKey().equals(o2.getKey())){
            return o1.getValue().compareTo(o2.getValue());
        }

        return 0;
    }

}

答案:

Key : a , value :0
Key : a , value :2
Key : a , value :5
Key : a , value :6