How to get inverse of a comparator in java

前端 未结 4 1521
执念已碎
执念已碎 2021-01-18 01:07

In a method I receive a generic object E extends Comparable as an argument. Now i want to create two priority queues.One which uses the comparato

相关标签:
4条回答
  • 2021-01-18 01:26

    The single argument of Collections.reverseOrder is a Comparator and not a Collection. For your code simply use reverseOrder without an argument. You have to use a non-zero inital size, too. The following code will work.

    queue2=new PriorityQueue<E>(1, Collections.reverseOrder());
    
    0 讨论(0)
  • 2021-01-18 01:34

    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.

    0 讨论(0)
  • 2021-01-18 01:36

    Below Program depicts how to do it.

    I have StringLengthComparator which compares based on string length. Using Collections.reverseOrder I have created queue which is reverse ordered and another queue which is ordered correctly.

    import java.util.Collections;
    import java.util.Comparator;
    import java.util.PriorityQueue;
    
    public class TestReverseorder {
    public static void main(String[] args) {
        Comparator<String> comparator = new TestReverseorder().new StringLengthComparator();
        PriorityQueue<String> reverse = new PriorityQueue<String>(10,
                Collections.reverseOrder(comparator));
        PriorityQueue<String> queue = new PriorityQueue<String>(10,comparator);
        queue.add("1");
        queue.add("12");
        queue.add("123");
    
        reverse.add("1");
        reverse.add("12");
        reverse.add("123");
    
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    
        while (!reverse.isEmpty()) {
            System.out.println(reverse.poll());
        }
    
    
    }
    
    public class StringLengthComparator implements Comparator<String> {
        @Override
        public int compare(String x, String y) {
            // Assume neither string is null. Real code should
            // probably be more robust
            if (x.length() < y.length()) {
                return -1;
            }
            if (x.length() > y.length()) {
                return 1;
            }
            return 0;
        }
    }
    }
    

    It will print output

    Normal Order:
    1
    12
    123
    Reverse Order:
    123
    12
    1
    
    0 讨论(0)
  • 2021-01-18 01:49

    Look at Collections.reverseOrder.

    0 讨论(0)
提交回复
热议问题