Home > Blockchain >  Comparator inside comparator?
Comparator inside comparator?

Time:09-30

I am making a program that sorts workers to workplaces. I have made a basic comparator (comp) that sorts on how many workers a workplace needs and it works fine. I have put this into a priority queue;

PriorityQueue<Workplaces> workplaces = new PriorityQueue<>(comp);

So the workplaces that needs most workers get them first. But if two workplaces needs the same amount of workers i want to compare these. If two workplaces needs 10 workers, i want to compare which workplace has the shortest avg distance to all workers. The one with the least avg distance gets the workers.

If the comparator returns 0 i want to compare these elements again.

So the question is how can I compare after I've passed the first comparator inside the priorityqueue? (I dont HAVE to use a priorityqueue)

CodePudding user response:

Use Comparator.thenComparing methods.

If you have workerCountComparator and distanceComparator you can use workerCountComparator.thenComparing(distanceComparator) to get what you need.

You can combine more then two comparators by calling this method multiple times:

c1.thenComparing(c2)
  .thenComparing(c3)
  .thenComparing(c4);
  • Related