简体   繁体   中英

Comparator inside comparator?

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)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM