Difference between PriorityQueue and TreeSet in Java?

Published May 09, 2022

New Java programmers can find it difficult to understand the difference between the PriorityQueue and TreeSet collections. This is because they both have a lot of functional similarities. For instance, they both offer O (log (N)) time complexity for adding and searching elements; both are non-synchronized and present elements in sorted order. The two, however, differ greatly from each other.  This post will discuss various differences between the Java TreeSet and the PriorityQueue.

The Differences between PriorityQueue and TreeSet in Java

Here are various differences between the PriorityQueue and TreeSet in Java

  • First of all, TreeSet is a Set, and therefore, like all Sets, it does not allow duplicate elements, while priorityQueue is a Queue, and therefore, it allows duplicate elements as well. This implies that PriorityQueue can contain multiple elements with equal values.

  • Unlike the PriorityQueue, which allows you to retrieve both the smallest and largest elements in 0(1) time, the TreeSet does not allow you to retrieve either the largest or smallest elements in 0(1) time.

  • In priorityQueue, aside from the root, all elements can or may ignore the order, while TreeSets always present all elements in sorted order.

 

Examples

Example of a TreeSet

import java.util.TreeSet;

public class TreeSet_Example {

            public static void main(String[] args) {

        TreeSet<String> treeseta = new TreeSet<String>();

        treeseta.add("Tomato");

        treeseta.add("Carrots");

        treeseta.add("Cabage");

        System.out.println("Tree Set is " + treeseta);

        String check = "Tomato";

        System.out.println("Contains " + check + " "

                           + treeseta.contains(check));

        System.out.println("First Value " + treeseta.first());

        System.out.println("Last Value " + treeseta.last());

        String val = "Tomato";

        System.out.println("Higher " + treeseta.higher(val));

        System.out.println("Lower " + treeseta.lower(val));

            }

}

 

Output:

Contains Tomato true

First Value Cabbage

Last Value Tomato

Higher null

Lower Carrots

 

Example of PriorityQueue

import java.util.PriorityQueue;

public class PriorityQueue_Example {

            public static void main(String[] args) {

        PriorityQueue<String> prioritiseQueue = new PriorityQueue<>();

        prioritiseQueue.add("Chicken");

        prioritiseQueue.add("Beef");

        prioritiseQueue.add("Fish");

        System.out.println(prioritiseQueue.peek());

        System.out.println(prioritiseQueue.poll());

        System.out.println(prioritiseQueue.peek());

            }

}

 

Output

Beef

Beef

Chicken

 

Keywords: Difference between PriorityQueue and TreeSet

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

111 Views