Sorting HashMap by value using a TreeMap and Comparator

前端 未结 3 655
离开以前
离开以前 2021-01-29 00:48

Im using the following code to create a hashmap and then sort the values in the hashmap by using a treemap and a comparator. However, the output is rather unexpected. So any th

3条回答
  •  独厮守ぢ
    2021-01-29 01:34

    What you are doing is really a misuse of tools.

    I believe what you need to do is:

    1. Have a list/array of input words (still fine that you get it by splitting the input string)
    2. Create a Map to store the word as key, and frequency as value
    3. Have a collection of unique words, then sort the collection base on the the frequency
    4. When you are doing the output, traverse the sorted unique word list, for each element, get the frequency from the frequencyMap, and output the word + frequency.

    Of course you can still make use of something like a TreeSet and use frequency as key, but you should have list of words as the value of this map (aka Multi-Map), instead of writing a problematic comparator which do not follow the contract of Comparator: http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html#compare%28T,%20T%29 Both your original implementation and the one in comment of one of the answers does not comply with the rule of sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y (The original one is even worse).

    some code snippet just for giving you hints:

    List words = ....;
    Map wordFrequencyMap = new HashMap();
    // iterate words and update wordFrequencyMap accordingly
    List uniqueWords = new ArrayList(new HashSet(words));
    Collections.sort(uniqueWords, new WordFrequencyComparator(wordFrequencyMap));
    for (String w : uniqueWords) {
      System.out.println("word : " + w + "  frequency : " + wordFrequencyMap.get(w));
    }
    

    The missing part shouldn't be anything difficult.

提交回复
热议问题