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 comparisonstring
.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
Post a Comment