Add Key and Value into an Priority Queue and Sort by Key in Java -


i trying take in list of strings , add them priority queue key , value. key being word , value being string value of word. need sort queue highest string value first. priority queue not letting me add 2 values.

public static list<string> pqsortstrings(list<string> strings) {     priorityqueue<string, integer> q = new priorityqueue<>();      (int x = 0; x < strings.size(); x++) {         q.add(strings.get(x),calculatestringvalue(strings.get(x)));     }     return strings; } 

problem

priorityqueue can store single object in it's each node. trying can not done is.

but can compose both objects in single class , use priorityqueue.

you either need supply comparator or rely on natural ordering implementing comparable interface.


solution

  • create class has string , int it's members.

    public class entry {     private string key;     private int value;      // constructors, getters etc. } 
  • implement comparable interface , delegate comparison string.

    public class entry implements comparable<entry> {     private string key;     private int value;      public entry(string key, int value) {         this.key = key;         this.value = value;     }      // getters      @override     public int compareto(entry other) {         return this.getkey().compareto(other.getkey());     } } 
  • build priorityqueue using class.

    priorityqueue<entry> q = new priorityqueue<>(); 
  • add elements following.

    q.add(new entry(strings.get(x), calculatestringvalue(strings.get(x)))); 

hope helps.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -