- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Max Heap in Java
Max heap is a complete binary tree, wherein the value of a root node at every step is greater than or equal to value at the child node.
Below is an implementation of Max Heap using library functions.
Example
import java.util.*; public class Demo{ public static void main(String args[]){ PriorityQueue<Integer> my_p_queue = new PriorityQueue<Integer>(Collections.reverseOrder()); my_p_queue.add(43); my_p_queue.add(56); my_p_queue.add(99); System.out.println("The elements in the priority queue are : "); Iterator my_iter = my_p_queue.iterator(); while (my_iter.hasNext()) System.out.println(my_iter.next()); my_p_queue.poll(); System.out.println("After removing an element using the poll function, the queue elements are :"); Iterator<Integer> my_iter_2 = my_p_queue.iterator(); while (my_iter_2.hasNext()) System.out.println(my_iter_2.next()); Object[] my_arr = my_p_queue.toArray(); System.out.println("The array representation of max heap : "); for (int i = 0; i < my_arr.length; i++) System.out.println("Value: " + my_arr[i].toString()); } }
Output
The elements in the priority queue are : 99 43 56 After removing an element using the poll function, the queue elements are : 56 43 The array representation of max heap : Value: 56 Value: 43
A class named Demo contains the main function. Inside the main function, an instance of priority queue is defined and elements are added into it using the ‘add’ function. An iterator is defined and it
is used to iterate over the elements in the priority queue. The ‘poll’ function is used to remove an element from the list. Next, the elements are iterated over and displayed on the screen.
- Related Articles
- Convert min Heap to max Heap in C++
- Is Max Heap in Python?
- Convert BST to Max Heap in C++
- Program to check heap is forming max heap or not in Python
- C++ Program to Implement Max Heap
- Minimum element in a max heap in C++.
- Insertion into a Max Heap in Data Structure
- Deletion from a Max Heap in Data Structure
- K-th Greatest Element in a Max-Heap in C++
- LongStream max() method in Java
- DoubleStream max() method in Java
- IntStream max() method in Java
- Ints max() function in Java
- Difference between Stack and Heap memory in Java
- How to change/increase the heap size of the Java Virtual Machine in Java?

Advertisements