How to get inverse of a comparator in java

前端 未结 4 1514
执念已碎
执念已碎 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: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 comparator = new TestReverseorder().new StringLengthComparator();
        PriorityQueue reverse = new PriorityQueue(10,
                Collections.reverseOrder(comparator));
        PriorityQueue queue = new PriorityQueue(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 {
        @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
    

提交回复
热议问题