Потеря данных при передаче данных из TreeMap в TreeSet. - PullRequest
0 голосов
/ 06 мая 2018

У меня есть 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 голосов
/ 06 мая 2018

Чтобы избежать таких ошибок, стоит использовать компаратор в Java 8:

Comparator.comparing(Map.Entry::getValue)


SortedSet<Map.Entry<String, Integer>> wordCountSortedByCount = 
new TreeSet<>(Comparator.comparing(Map.Entry::getValue));
0 голосов
/ 06 мая 2018

Изменить return o1.getValue().compareTo(o1.getValue()); в return o1.getValue().compareTo(o2.getValue());

Выход будет 2.

...