# Queue with multi-field sorting on priority and time

### Intent

Implement a task queue with sorting based on 1) priority and 2) time, specifically, time at which task was created or time-stamped (not inserted in the queue), giving preference to tasks with older time stamps.

### Tried

This is what I got so far; much simpler than I thought having assumed it would require more than just a single `PriorityQueue`. In the comparator, if two priorities are equal, another comparison is made on `Task.time`, otherwise, comparison is based on just `Task.priority`.

``````import java.util.Comparator;
import java.util.PriorityQueue;

public class QueueWithPriorityAndTimeSort {
High, Medium, Low
}

long time;

time = t;
priority = p;
}

}
}

if( compareResult == 0){
//same priority, now compare on time
compareResult = 1;
else
compareResult = -1;
}
return compareResult;
}
}

public void buildAndTestQueue(){

while ((m = queue.poll()) != null)
System.out.println(
String.format("Priority: %s, %d", m.priority, m.time));
}

public static void main(String args[]) {
QueueWithPriorityAndTimeSort queueTest =
new QueueWithPriorityAndTimeSort();
queueTest.buildAndTestQueue();
}
}
``````

### Question

Is this a valid approach? I don't believe the added comparator logic changes the time complexity; aside from that, I don't see any glaring issues.

957

#### raffian

Separating these concerns allows sorting based on specific needs for increased flexibility

There are better ways to separate the concerns and make your code even more flexible such that you can change the sorting strategy without changing your code. Sounds exciting?

Let's start by defining a Comparator just for comparaing priorities :

``````class HighPriorityComparator implements Comparator<Task> {
}
}
``````

Let's define a Comparator just for comparing time :

``````class TimeComparator implements Comparator<Task> {
int compareResult = 0;
compareResult = 1;
else
compareResult = -1;

return compareResult;
}
}
``````

Now for the best part. Let's define a Comparator that will allow you to mix and match comparison logic.

``````class MixAndMatchComparator implements Comparator<Task> {

this.comparators=comparators;
}

@Override
int compareResult = 0;
if(comparator.compare(o1, o2)!=0) {
return comparator.compare(o1, o2);
}
}
return compareResult;
}

}
``````

Now let's sort on priority and if priority is equal, then sort on time :

``````List<Comparator<Task>> comparators = new ArrayList<Comparator<Task>>();
//first sort on priority
//then on time
MixAndMatchComparator orComparator = new MixAndMatchComparator(comparators);
``````

Wait! You changed your mind? You now want to sort on time and if time is equal, then on priority? Just change the order in which you add the comprators to the list :

``````List<Comparator<Task>> comparators = new ArrayList<Comparator<Task>>();
//first sort on time
//then on priority