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

时间:2018-05-06 11:12:03

标签: java treemap treeset sortedset

我有一个像这样的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());

2 个答案:

答案 0 :(得分:2)

为避免此类错误,值得在Java 8中使用比较器:

Comparator.comparing(Map.Entry::getValue)


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

答案 1 :(得分:1)

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

输出为2。