how to take max value from priority queue in java

ht‮w//:spt‬ww.lautturi.com
how to take max value from priority queue in java

To take the maximum value from a PriorityQueue in Java, you can use the peek method to retrieve the element at the head of the queue, or the poll method to remove and return the element at the head of the queue.

Here's an example of how you can use the peek method to retrieve the maximum value from a PriorityQueue:

import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        // Create a priority queue with integers
        PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a);

        // Add some elements to the queue
        queue.add(10);
        queue.add(20);
        queue.add(30);

        // Retrieve the maximum value from the queue
        int max = queue.peek();

        System.out.println("Maximum value: " + max);
    }
}

This code will create a PriorityQueue with integers and add some elements to the queue. The PriorityQueue is configured to use the default natural ordering of the elements, which orders the elements in ascending order. To retrieve the maximum value from the queue, we use the peek method to retrieve the element at the head of the queue, which will be the maximum value.

The output of this code will be:

Maximum value: 30

Here's an example of how you can use the poll method to remove and return the maximum value from a PriorityQueue:

import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        // Create a priority queue with integers
        PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a);

        // Add some elements to the queue
        queue.add(10);
        queue.add(20);
        queue.add(30);

        System.out.println(queue);
        // Remove and return the maximum value from the queue
        int max = queue.poll();

        System.out.println("Maximum value: " + max);
        System.out.println(queue);
	}
}

output:

[30, 10, 20]
Maximum value: 30
[20, 10]
Created Time:2017-11-01 20:43:02  Author:lautturi