如何按值对 TreeSet 进行排序?

How to sort a TreeSet by Value?

我对 TreeMapTreeSet 等很陌生,想知道如何按值对数据结构进行排序?我意识到使用 TreeSet 可以自动将其排序为字母顺序,但我希望它按值排序?知道如何做到这一点吗?

它目前打印成...

当我想让它打印成...

这是我的方法...

ArrayList<String> fullBagOfWords = new ArrayList<String>();
public Map<String, Integer> frequencyOne;

public void termFrequency() throws FileNotFoundException{
    Collections.sort(fullBagOfWords);
    Set<String> unique = new TreeSet<String>(fullBagOfWords);
    PrintWriter pw = new PrintWriter(new FileOutputStream(frequencyFile));
    pw.println("Words in Tweets :   Frequency of Words");
    for (String key : unique) {
        int frequency = Collections.frequency(fullBagOfWords, key);

        System.out.println(key + ": " + frequency);
        pw.println(key + ": " + frequency);
        }
    pw.close();
    }

感谢大家的帮助。

TreeMap 按键排序,我认为您不能使用相同的实现来按值排序。但是您可以使用稍微不同的方法来完成任务:

public Map<String, Integer> countWords(List<String> words) {
    Map<String, Integer> result = new Map<>();
    for (String word : words) {
        if (result.containsKey(word)) {
            // the word is already in the map, increment the count
            int count = result.get(word) + 1;
            result.put(word, count);
        } else {
            result.put(word, 1);
        }
    }

    return result;
}

然后您只需要对生成的地图的元素进行排序。您可以通过以下方式执行此操作:

public List<Map.Entry<String, Integer> sortMap(Map<String, Integer> map) {
    List<Map.Entry<String, Integer> elements = new LinkedList<>(map.entrySet());
    Collections.sort(elements, new Comparator<Map.Entry<String, Integer>>() {

        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) {
            return o1.getValue().compareTo(o2.getValue());
        }

    });
}

所以你用第一种方法统计词频,第二种方法排序。

尝试这样的事情:

Set<Map.Entry<Integer, Integer>> sorted = 
      new TreeSet<Map.Entry<Integer, Integer>>(new Comparator<Map.Entry<Integer, Integer>> {
    public int compare(Map.Entry<Integer, Integer> first, Map.Entry<Integer, Integer> second) {
       return first.getValue().compareTo(second.getValue());
    }

    public boolean equals(Map.Entry<Integer, Integer> that) {
        return this.equals(that);
    }
});

那应该给你你想要的。

您可以创建一个 ArrayList 并将每个条目存储在其中,如下所示:

ArrayList<Map.Entry<String, Integer> list = new new ArrayList(map.entrySet());

然后您可以使用按条目值比较条目的比较器对 arrayList 进行排序:

Collections.sort(list , new Comparator<Map.Entry<String, Integer>>() {

        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) {
            return o1.getValue().compareTo(o2.getValue());
        }

    });

然后您可以打印 arrayList 中的条目