0

I am trying to dequeue based off the integer value in my priority queue, rather than the name (String) value. For instance, [Sally, 4] should be pulled before [John, 1]. Because 4 is higher in priority than 1. However the way I have structured my Queue, it is polling by alphabet from the first variable (name). Any step in the right direction would be greatly appreciated, thank you.

package stackqueuewood;
import java.util.PriorityQueue;
import java.util.ArrayList;

public class StackQueueWood {

public static void main(String[] args) {

    ArrayList<String> people = new ArrayList<>();

        people.add(person("Tom", 3));
        people.add(person("Dick", 4));   
        people.add(person("Harry", 2));                 

    PriorityQueue<String> pQ = new PriorityQueue<>();

        pQ.addAll(people);
        System.out.println("The current queue size is: " + pQ.size());
        System.out.println("The current queue is: \n" + pQ);

        System.out.println(pQ.peek());
        pQ.poll();
        System.out.println(pQ);
}
public static String person(String name, int priority){

    return ("(" + name + ", " + priority + ")");
 }  
}
  • Possible duplicate of [How do I use a PriorityQueue?](https://stackoverflow.com/questions/683041/how-do-i-use-a-priorityqueue) – GBlodgett Jul 13 '18 at 00:49
  • So where in that does it explain what I am asking, because I cannot find it sadly. Those show single parameter objects. – Lulzmafoo Gaming Jul 13 '18 at 01:05
  • You'll have to actually create a class to model the `person`. Then the approach should be much the same – GBlodgett Jul 13 '18 at 01:19
  • So the method person should be removed, and a separate class created that does the same thing correct? that way the class works as a constructor that can be manipulated? where as the method I have cannot be manipulated? – Lulzmafoo Gaming Jul 13 '18 at 01:59

2 Answers2

0

Rather than concatenating the two values together into a String, create a new class to represent a person, with fields for name and priority. Then you can use a PriorityQueue<Person> and specify the Comparator to use (probably Comparator.comparingInt(Person::getPriority)).

VeeArr
  • 6,039
  • 3
  • 24
  • 45
0

You need:

Comparator<String> orderIsdn =  new Comparator<String>() { 
    //Your sorting method
} 

then:

PriorityQueue<String> pQ = new PriorityQueue<>(orderIsdn);
GBlodgett
  • 12,704
  • 4
  • 31
  • 45
wwd
  • 1
  • 1
  • Use formatting tools to make your post more readable. Use `code blocking` for code and log and error texts and **bold** and *italics* to highlight things. also elaborate your answer. – Morse Jul 13 '18 at 01:30