0

I'm trying to insert sorted values into a queue in Java. I've created a compareTo method and need help adding it to the Queue. The compareTo method is in one class and the queue is in a different class.

compareTo method:

public int compareTo(Event cmp) {
        if(getArrTime() > cmp.arrTime) {
            return 1;
        }
        else if(getArrTime() < cmp.arrTime) {
            return -1;
        }
        else {
            return 0;
        }
    }

This is what I'm trying to do for the insert method:

public void enque(Object insertSort) {
        //if compareTo is greater than param, append to the front
        //if equal, use event type. If it's 'A' append before 'D'
        //if compareTo is less than the param, add to end
        //return list
    }
Sam Jones
  • 45
  • 11

1 Answers1

1

What impl of Queue are you using? Have you looked at a PriorityQueue? It's a sorted queue using Comparators.

See the answers to this question: Sorted collection in Java

Here's a working example using Event from your question and sorting by eventType property alphabetically:

PriorityQueue<Event> queue = new PriorityQueue<>(
    new Comparator<Event>() {

        @Override
        public int compare(Event o1, Event o2) {
            int result = o1.getEventType()
                .compareTo(o2.getEventType()); 
            return result;
        }
                
});

queue.add(new Event("C"));
queue.add(new Event("A"));
queue.add(new Event("B"));    
    
while(!queue.isEmpty()) {
    System.out.println(queue.poll().getEventType());
}

Prints: A B C

Kevin Hooke
  • 2,583
  • 2
  • 19
  • 33
  • Hey Kevin, I'm using the LinkedList implementation of the Queue. – Sam Jones Apr 01 '21 at 00:21
  • 1
    There isn't a sorted impl of a List in Java Collections, but there is the SortedSet interface with the TreeSet impl. Take a look at the link in my answer above. – Kevin Hooke Apr 01 '21 at 00:24
  • I decided to use the PriorityQueue but I have a follow-up question. How would I sort it based on the character? I want the characters with 'A' to come before 'D' in the queue. – Sam Jones Apr 01 '21 at 01:11
  • Updated with a working example showing usage – Kevin Hooke Apr 01 '21 at 02:20