Sorting words in order of frequency? (least to greatest)

前端 未结 4 2389
孤独总比滥情好
孤独总比滥情好 2021-01-06 07:05

does any one have any idea how to sort a list of words in the order of their frequency (least to greatest) using the built in collection.sort and a compar

4条回答
  •  灰色年华
    2021-01-06 07:43

    A solution, close to your original posting with corrections and the sorting as suggested by Torious in the comments:

    import java.util.*;
    
    public class Parser implements Comparator  {
    
        public Map wordCount;
    
        void parse ()
        {
            Scanner scanner = new Scanner (System.in);
    
            // don't redeclare it here - your attribute wordCount will else be shadowed
            wordCount = new HashMap ();
    
            //iterates through each word in the text file
            while (scanner.hasNext ()) {
                String word = scanner.next ();
                // operate on the word, not on next and next of next word from Scanner
                word = word.replaceAll (" [^A-Za-z0-9]", " ");
                word = word.toLowerCase ();
                // look into your map:
                if (! wordCount.containsKey (word))
                    wordCount.put (word, 1);
                else
                    wordCount.put (word, wordCount.get (word) + 1);;
            }
        }
    
        public int getCount (String word) {
            return wordCount.get (word);
        }
    
        public int compare (String w1, String w2) {
            return getCount (w1) - getCount (w2);
        }
    
        public List getWordsInOrderOfFrequency () {
            List justWords = new ArrayList (wordCount.keySet());
            Collections.sort (justWords, this);
            return justWords; 
        }
    
        public static void main (String args []) {
            Parser p = new Parser ();
            p.parse ();
            List ls = p.getWordsInOrderOfFrequency ();
            for (String s: ls) 
                System.out.println (s);
        }
    }
    

提交回复
热议问题