如果值是实例,则TreeMap按值排序

时间:2018-10-19 16:32:53

标签: java treemap comparable

我应该编写一个比较器,该实例将使我可以通过getScore对TreeMap进行排序,该实例为Value而不是默认的自然顺序。 早些时候,我找到了解决问题的一个决定(TreeMap sort by value),但问题仍然存在。当我调用e1.getValue时,它们不会解析实例方法。我如何获得它们?

public class Trending {

        Map<String, Topic> treeMap = new TreeMap<>();


        void initialScore(int id, String topic, int score){
            Topic object = new Topic(id, topic, score);
            treeMap.put(topic, object);
        }



        static <String, Topic extends Comparable<Topic>>
        SortedSet<Map.Entry<String,Topic>> entriesSortedByValues(Map<String,Topic> map) {
            SortedSet<Map.Entry<String,Topic>> sortedEntries = new TreeSet<Map.Entry<String,Topic>>(
                    new Comparator<Map.Entry<String,Topic>>() {
                        @Override public int compare(Map.Entry<String,Topic> e1, Map.Entry<String,Topic> e2) {
                            int res = e1.getValue().compareTo(e2.getValue());
                            return res != 0 ? res : 1;
                        }
                    }
            );
            sortedEntries.addAll(map.entrySet());
            return sortedEntries;
        }

    }

1 个答案:

答案 0 :(得分:0)

您可以将您的entriesSortedByValues方法声明为非通用方法(这将隐藏Topic类,如您的问题的第一条评论所述):

static SortedSet<Map.Entry<String, Topic>> entriesSortedByValues(Map<String, Topic> map) {
        SortedSet<Map.Entry<String, Topic>> sortedEntries = new TreeSet<Map.Entry<String, Topic>>(
            new Comparator<Map.Entry<String, Topic>>() {
                @Override
                public int compare(Map.Entry<String, Topic> e1, Map.Entry<String, Topic> e2) {
                    int res = e1.getValue().compareTo(e2.getValue());
                    return res != 0 ? res : 1;
                }
            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
}

,然后使您的Topic类实现Comparable

public class Topic implements Comparable<Topic> {
    private final int id;
    private final String topic;
    private final int score;

    public Topic(int id, String topic, int score) {
        this.id = id;
        this.topic = topic;
        this.score = score;
    }

    public int getScore() {
        return score;
    }

    @Override
    public int compareTo(Topic o) {
        return Integer.compare(getScore(), o.getScore());
    }
}