Open In App

Difference Between PriorityQueue and TreeSet

Last Updated : 28 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The PriorityQueue and TreeSet both are the classes defined inside the Collection Framework. In this article, we will learn the differences between PriorityQueue and TreeSet. PriorityQueue is an implementation of Queue interface and the TreeSet is the implementation of the Set interface. There are some differences exists between them. So we have tried to list out the differences between PriorityQueue and TreeSet.

1. PriorityQueue: A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.  

PriorityQueue Demo:

Java




// Java program to demonstrate the
// working of PriorityQueue
import java.util.*;
  
class PriorityQueueDemo {
  
    // Main Method
    public static void main(String args[])
    {
        // Creating empty priority queue
        PriorityQueue<String> pQueue
            = new PriorityQueue<>();
  
        // Adding elements to the pQueue using add()
        pQueue.add("Geeks");
        pQueue.add("For");
        pQueue.add("Geeks");
  
        // Printing the top element of PriorityQueue
        System.out.println(pQueue.peek());
  
        // Printing the top element and removing it
        // from the PriorityQueue container
        System.out.println(pQueue.poll());
  
        // Printing the top element again
        System.out.println(pQueue.peek());
    }
}


Output

For
For
Geeks

2. TreeSet: TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class.

TreeSet Demo:

Java




// Java code to demonstrate
// the working of TreeSet
  
import java.util.*;
class TreeSetDemo {
  
    public static void main(String[] args)
    {
        // Creating an empty TreeSet
        TreeSet<String> ts = new TreeSet<String>();
  
        // Elements are added using add() method
        ts.add("Geek");
        ts.add("For");
        ts.add("Geeks");
  
        System.out.println("Tree Set is " + ts);
  
        String check = "Geeks";
  
        // Check if the above string exists in
        // the treeset or not
        System.out.println("Contains " + check + " "
                           + ts.contains(check));
  
        // Print the first element in
        // the TreeSet
        System.out.println("First Value " + ts.first());
  
        // Print the last element in
        // the TreeSet
        System.out.println("Last Value " + ts.last());
  
        String val = "Geek";
  
        // Find the values just greater
        // and smaller than the above string
        System.out.println("Higher " + ts.higher(val));
        System.out.println("Lower " + ts.lower(val));
    }
}


Differences between PriorityQueue and TreeSet

                   PriorityQueue

                                TreeSet

PriorityQueue uses the Queue underlying data structure TreeSet uses the Set underlying data structure.
PriorityQueue allows the duplicate elements TreeSet doesn’t allow the duplicate elements
In PriorityQueue, apart from the root rest of the elements may or may not follow any order. In TreeSet all the elements remain in the sorted order.
Using PriorityQueue, we can retrieve largest or smallest element in O(1) time. TreeSet doesn’t provide a way to retrieve largest or smallest element in O(1) time, but since they are in sorted order it gets the first or last element in O(1) time.
PriorityQueue comes in JDK 1.5. TreeSet comes in JDK 1.4.


Similar Reads

Difference Between heapq and PriorityQueue in Python
In this article, we are going to see the difference between heapq and PriorityQueue in Python. Differences between PriorityQueue and heapqPython queue PriorityQueue is thread-safe, but heapq doesn't guarantee thread safety.PriorityQueue implements locking to ensure thread safety, thus it is slower than heapq.heapq heapifies the original list inplac
3 min read
Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHashSet, and TreeSet in java. Differences Between Ha
6 min read
Difference Between TreeSet and SortedSet in Java
TreeSet is one of the implementations of the Navigable sub-interface. It is underlying data structure is a red-black tree. The elements are stored in ascending order and more methods are available in TreeSet compare to SortedSet. We can also change the sorting parameter using a Comparator. For example, Comparator provided at set creation time, depe
3 min read
Difference Between EnumSet and TreeSet in Java
EnumSet and TreeSet both are the classes defined inside the collection framework. But there are few differences exists between them. In this article, we have tried to cover all these differences between them. 1. EnumSet: EnumSet is a specialized implementation of the Set interface for enumeration types. It extends AbstractSet and implements the Set
3 min read
Difference between TreeMap and TreeSet in Java
TreeSet is mainly an implementation of SortedSet in java where duplication is not allowed and objects are stored in sorted and ascending order. Some important features of the TreeSet are: In TreeSet duplicate values are not allowed because it implements the SortedSet interface.Objects in a TreeSet are stored in ascending order.In TreeSet the insert
2 min read
How to Convert a PriorityQueue into an Array, List, and Set in Java?
In Java, PriorityQueue is an implementation of the Queue interface. It means high-priority elements can be saved first compared to lower-priority elements in the queue, and it follows the natural order of elements. In this article, we will learn how to convert a PriorityQueue into an Array, List, and Set in Java. Approach to convert a PriorityQueue
3 min read
How to Handle Concurrent Access and Modification of a PriorityQueue in Java?
In Java, PriorityQueue is a class that implements a priority queue based on the priority heap. While PriorityQueue provides efficient operations for the adding and removing elements and it is not inherently thread-safe. Concurrent access and modification of the PriorityQueue can lead to unexpected behavior or runtime exceptions in the multi-threade
3 min read
PriorityQueue toArray() Method in Java
The java.util.PriorityQueue.toArray() method in Java is used to form an array of the same elements as that of the Priority Queue. Basically, it copies all the element from a priority queue to a new array. Syntax: Object[] arr = Priority_Queue.toArray() Parameters: The method does not take any parameters. Return Value: The method returns an array co
3 min read
Implement PriorityQueue through Comparator in Java
Prerequisite : Priority Queue, Comparator Priority Queue is like a regular queue, but each element has a "priority" associated with it. In a priority queue, an element with high priority is served before an element with low priority. For this, it uses a comparison function which imposes a total ordering of the elements. The elements of the priority
3 min read
PriorityQueue comparator() Method in Java
The java.util.PriorityQueue.comparator() method shares an important function of setting and returning the comparator that can be used to order the elements in a PriorityQueue. The method returns a null value if the queue follows the natural ordering pattern of the elements.Syntax: comp_set = (PriorityQueue)Priority_Queue.comparator() Parameters: Th
2 min read