打印使用优先级队列排序的哈希图实例

时间:2019-05-12 11:06:41

标签: java hashmap hashtable priority-queue

我已经插入了txt文件的各个单词,并分别在哈希图中重复了几次作为键和值。问题是,我想使用PQ按降序打印k个最常用的单词,但是尽管将值插入整数优先级队列似乎很容易,然后获得k个max整数,但我无法弄清楚再次获取与每个值对应的键以进行打印的方法(这些值可能不是唯一的)。一种解决方案是反转哈希图,但这似乎不是“安全”的选择。

public static void main(int k)throws IOException{

   //Create input stream & scanner
   FileInputStream file = new FileInputStream("readwords.txt");
   Scanner fileInput = new Scanner(file);

   Map<String, Integer> frequency = new HashMap<>();
   LinkedList<String> distinctWords = new LinkedList<String>();
   PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();

   //Read through file and find the words
   while(fileInput.hasNext()){
       //Get the next word
       String nextWord = fileInput.next().toLowerCase();
       //Determine if the word is in the HashMap
       if(frequency.containsKey(nextWord)) {
           frequency.put(nextWord, frequency.get(nextWord) + 1);
       }
       else {
            frequency.put(nextWord, 1);
            distinctWords.add(nextWord);
       }


    }

    //Close
    fileInput.close();
    file.close();



}

1 个答案:

答案 0 :(得分:1)

可能有多种解决方案,这里是我的。创建具有两个字段的class;一个用于String,另一个用于Integer。使类实现Comparable并覆盖方法compareTo,以便比较Integers

public class WordFrequency implements Comparable<WordFrequency> {
    private String word;
    private Integer frequency;

    public WordFrequency(String word, Integer frequency) {
        this.word = word;
        this.frequency = frequency;
    }

    // descending order
    @Override
    public int compareTo(WordFrequency o) {
        return o.getFrequency() - this.getFrequency();
    }

    public Integer getFrequency() {
        return this.frequency;
    }

    @Override
    public String toString() {
        return word + ": " + frequency;
    }
}

然后,将您的map<String, Integer>转换为PriorityQueue<WordFrequency>

PriorityQueue<WordFrequency> pQueue = frequency.entrySet().stream()
        .map(m -> new WordFrequency(m.getKey(), m.getValue()))
        .collect(Collectors.toCollection(PriorityQueue::new));

如果要打印,则必须使用poll(),否则不能保证顺序。

while(!pQueue.isEmpty())
        System.out.println(pQueue.poll());