Change priorityQueue to max priorityqueue

后端 未结 17 1837
一整个雨季
一整个雨季 2020-12-04 05:13

I have priority queue in Java of Integers:

 PriorityQueue pq= new PriorityQueue();

When I call pq.poll(

17条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 06:01

    You can use lambda expression since Java 8.

    The following code will print 10, the larger.

    // There is overflow problem when using simple lambda as comparator, as pointed out by Фима Гирин.
    // PriorityQueue pq = new PriorityQueue<>((x, y) -> y - x);
    
    PriorityQueue pq =new PriorityQueue<>((x, y) -> Integer.compare(y, x));
    
    pq.add(10);
    pq.add(5);
    System.out.println(pq.peek());
    

    The lambda function will take two Integers as input parameters, subtract them from each other, and return the arithmetic result. The lambda function implements the Functional Interface, Comparator. (This is used in place, as opposed to an anonymous class or a discrete implementation.)

提交回复
热议问题