Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get inverse of a comparator in java

In a method I receive a generic object E extends Comparable<E> as an argument. Now i want to create two priority queues.One which uses the comparator used by E and other queue which uses the opposite of comparator used by E(i.e. if E uses '<' then second queue must use '>='). Please hep me how to create two such queues.

queue2=new PriorityQueue<E>(0,Collections.reverseOrder(e));

I am getting the error that reverseOrder is not applicable.

please help

like image 247
Abhinav Batra Avatar asked Sep 10 '12 04:09

Abhinav Batra


2 Answers

Look at Collections.reverseOrder.

like image 60
casablanca Avatar answered Oct 08 '22 00:10

casablanca


Your object E extends java.lang.Comparable, but it is not a java.util.Comparator.

Create your first queue w/o a Comparator and you'll get the ordering in your compareTo function, then create a java.util.Comparator that does the comparison in reverse (just call a.compareTo(b) and then negate the result) and create your second queue with that comparator.

like image 36
Bill Avatar answered Oct 07 '22 23:10

Bill