将数据从 TreeMap 传输到 TreeSet 时丢失数据。

Losing data when transferring data from TreeMap to TreeSet.

我有一个像这样的 TreeMap。

// Create a map of word and their counts.
// Put them in TreeMap so that they are naturally sorted by the words
Map<String, Integer> wordCount = new TreeMap<String, Integer>();
wordCount.put("but", 100);
wordCount.put("all", 10);

由于它是一个 TreeMap,因此内容按关键字排序,即单词。

    // Iterate over the map to confirm that the data is stored sorted by words.
    // This part is also working nicely and I can see that the ouput is sorted by
    // words.
    Set<String> words = wordCount.keySet();
    logger.debug("word, count");
    for (Iterator<String> itForWords = words.iterator(); itForWords.hasNext();) {
        String word = (String) itForWords.next();
        Integer count = wordCount.get(word);
        logger.debug("{}, {}", word, count);
    }

现在我正在尝试按计数对它们进行排序。由于 TreeMap 不会放弃我将它们移动到 SortedSet 的技巧。

    // Trying to sort the collection by the count now.
    // TreeMap cant be sorted on values.
    // Lets put them in a sorted set and put a comparator to sort based on values
    // rather than keys.
    SortedSet<Map.Entry<String, Integer>> wordCountSortedByCount = new TreeSet<Map.Entry<String, Integer>>(
            new Comparator<Map.Entry<String, Integer>>() {

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

            });
    wordCountSortedByCount.addAll(wordCount.entrySet());

此时我希望 TreeSet 有 2 个条目。但它只显示一个。请帮忙。

    // This is NOT WORKING
    // The size is only 1. It should have been two.
    logger.debug("Size of sorted collection is {}", wordCountSortedByCount.size());

修改return o1.getValue().compareTo(o1.getValue());到 return o1.getValue().compareTo(o2.getValue());

输出将为 2。

为避免此类错误,值得在 Java 8:

中使用比较器
Comparator.comparing(Map.Entry::getValue)


SortedSet<Map.Entry<String, Integer>> wordCountSortedByCount = 
new TreeSet<>(Comparator.comparing(Map.Entry::getValue));