Solution
public static List<String> pQSortStrings(List<String> strings) {
Queue<String> pq = new PriorityQueue<>((a, b) ->
calculateStringValue(b) - calculateStringValue(a));
for (String str : strings) {
pq.add(str);
}
return strings;
}
Explanation
I believe that the cleanest way to do this is to store Strings in your pq and use a small custom Comparator
.
In this case, we want to use calculateStringValue
and the pq should return highest String
values first. Therefore, make a pq of entries and use the following Comparator
:
1 Queue<String> pq = new PriorityQueue<>(new Comparator<String>() {
2 @Override
3 public int compare(String a, String b) {
4 return calculateStringValue(b) - calculateStringValue(a);
5 }
6 });
7 for (String str : strings) {
8 pq.add(str);
9 }
10 return strings;
Simpler syntax for the Comparator
, replacing lines 1 - 6, is:
Queue<String> pq = new PriorityQueue<>((a, b) ->
calculateStringValue(b) - calculateStringValue(a));
If you wanted to return smallest String
values first, you could just switch the order around for a
and b
in the Comparator
:
...new PriorityQueue<>((a, b) -> calculateStringValue(a) - calculateStringValue(b));
In general, the pattern a - b
sorts by smallest first, and b - a
sorts by largest values first.