How to use Java PriorityQueue with Examples

ozenero.com-java-priorityqueue-examples

[no_toc]In the tutorial, Grokonez introduces how to work with Java PriorityQueue by examples:

  • How does Java PriorityQueue work?
  • Explore Java PriorityQueue Hierarchy
  • Create Java PriorityQueue with Integer, String, and Custom Object Class

Related posts:
Java TreeMap with Examples

Java PriorityQueue

– Java PriorityQueue is an unbounded priority queue.
– The elements of the priority queue are ordered according to their natural ordering, or by a Comparator.

  • The front of the priority queue contains the least element.
  • And the rear of the priority queue contains the greatest element.

ozenero-howto-java-priority-queue-examples

– PriorityQueue does not permit null elements.
– PriorityQueue does not permit insertion of non-comparable objects. ClassCastException will be throwed.
– The head of this queue is the least element. The queue operations poll, remove, peek, and element access the element at the head of the queue.
– Java PriorityQueue is not synchronized. Multiple threads should not access the same PriorityQueue concurrently if having any of the threads modifies the queue.

Java PriorityQueue Hierarchy

ozenero-java-priority-queue-hierarchy-examples

Java PriorityQueue with Integer Example

In the follwing example, We create an Integer Java PriorityQueue, then do a list operations on the queue:

  • Insert an element to PriorityQueue with offer and add method.
  • Retrieve a head value of the Queue, but NOT remove it by peek() method.
  • Removes a single instance of the specified element from this queue by remove(Object o) method.
  • Retrieves and removes the head of this queue by poll() method.

Example:


import java.util.PriorityQueue;
import java.util.Queue;

public class JavaPriorityQueueExamples {

	public static void main(String[] args) {
		Queue intQueue = new PriorityQueue();
		// Inserts the specified element into this priority queue.
		intQueue.offer(10);
		intQueue.offer(1);
		intQueue.offer(5);
		intQueue.offer(9);
		
		// E poll(): Retrieves and removes the head of this queue
		System.out.println(intQueue.remove());
		/*
		 * 1
		 */
		
		// Retrieves, but does not remove, the head of this queue
		int head = intQueue.peek();
		System.out.println("headValue = " + head); // headValue = 5
		
		// Inserts the specified element into this priority queue.
		intQueue.add(7);
		intQueue.add(2);
		
		head = intQueue.element();
		System.out.println("headValue = " + head); // headValue = 2
		
		// Removes a single instance of the specified element from this queue, if it is present.
		boolean containOrNot = intQueue.remove(9);
		System.out.println(containOrNot); // true
		
		System.out.println("---");
		
		while(!intQueue.isEmpty()) {
			System.out.println(intQueue.poll());
		}
		
		/*
		 * 2
		 * 5
		 * 7
		 * 10
		 */
	}
}

– In above example, we use PriorityQueue() Constructor to create a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.

add() and offer() method, both can insert an element to a PriorityQueue, But what is the difference?
+ The offer method inserts an element if possible, otherwise returning false.
+ This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception.

– The remove() and poll() methods remove and return the head of the queue.
-> BUT when the queue is empty, the remove() method throws an exception, while the poll() method returns null.

– The element() and peek() retrive the head’s value of the queue and NOT remove. When the queue is empty:
+ element() throws NoSuchElementException.
+ peek() returns null.

Now we do an example to iterate all elements of a Java PriorityQueue:

– using iterator(): to return an iterator over the elements in the queue.
– using toArray(): to return an array containing all the elements in the queue.


import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;

public class JavaPriorityQueueExamples{

	public static void main(String[] args) {
		Queue<Integer> intQueue = new PriorityQueue<Integer>();
		// Inserts the specified element into this priority queue.
		intQueue.offer(10);
		intQueue.offer(1);
		intQueue.offer(5);
		intQueue.offer(9);
		
		// Returns an iterator over the elements in this queue.
		Iterator<Integer> intIterator = intQueue.iterator();
		
		while (intIterator.hasNext()) 
            System.out.print(intIterator.next() + " ");
		/*
		 * 1 9 5 10 
		 */
		
		System.out.println();
		
		// Returns an array containing all of the elements in this queue.
		Object[] intArr =  intQueue.toArray();
		for(int i=0; i<intArr.length; i++) {
			System.out.print(intArr[i] + " ");
		}
		/*
		 * 1 9 5 10 
		 */
	}
}

Java PriorityQueue with String Example

– Example: Create Java String PriorityQueue using Natural Ordering of String


import java.util.PriorityQueue;
import java.util.Queue;

public class JavaPriorityQueueExamples {

	public static void main(String[] args) {
		Queue strQueue = new PriorityQueue();
		
		// Inserts the specified element into this priority queue.
		strQueue.offer("Jack");
		strQueue.offer("Charlie");
		strQueue.offer("Joe");
		strQueue.offer("George");
		
		while(!strQueue.isEmpty()) {
			System.out.print(strQueue.poll() + " ");
		}
		
		/*
		 * -> Charlie George Jack Joe   
		 */
	}
}

Create Java PriorityQueue with a custom Comparator

– Create a Java PriorityQueue using a Custom Comparator that compares two Strings by their length:


import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class JavaPriorityQueueExamples {

	public static void main(String[] args) {
		Queue strQueue = new PriorityQueue((Comparator) new Comparator() {
            public int compare(String s1, String s2) {
                return s1.length() - s2.length();
            }
        });
		
		// Inserts the specified element into this priority queue.
		strQueue.offer("Jack");
		strQueue.offer("Charlie");
		strQueue.offer("Joe");
		strQueue.offer("George");
		
		while(!strQueue.isEmpty()) {
			System.out.print(strQueue.poll() + " ");
		}
	}
}

-> Output:


Joe Jack George Charlie

Java PriorityQueue with Custom Object Example

– Create an Java Developer class:


class Developer{
	Integer id;
	String name;
	Double salary;
	
	public Developer(Integer id, String name, Double salary){
		this.id = id;
		this.name = name;
		this.salary = salary;
	}
	
	public int getId() {
		return this.id;
	}
	
	public String getName() {
		return this.name;
	}
	
	public Double getSalary() {
		return this.salary;
	}
	
	public String toString() {
		return String.format("[id = %d, name = %s, salary = %.2f]", id, name, salary);
	}
}

– Implement Comparable interface to compare its elements and order them accordingly as below:


class Developer implements Comparable{
	...
	
	@Override
	public int compareTo(Developer d) {
        if(this.getSalary() > d.getSalary()) {
            return 1;
        } else if (this.getSalary() < d.getSalary()) {
            return -1;
        } else {
            return 0;
        }
	}
}

- Create a Java PriorityQueue Example with Developer class:


import java.util.PriorityQueue;
import java.util.Queue;

public class JavaPriorityQueueExamples {

	public static void main(String[] args) {
		Queue devQueue = new PriorityQueue();
		
		// Inserts the specified element into this priority queue.
		devQueue.offer(new Developer(1, "Jack", 6000.0));
		devQueue.offer(new Developer(4, "Joe", 7000.0));
		devQueue.offer(new Developer(10, "Davis", 6500.0));
		devQueue.offer(new Developer(6, "Mary", 5700.0));
		
		while(!devQueue.isEmpty()) {
			System.out.println(devQueue.poll());
		}		
	}
}

-> Output:


/*
 * [id = 6, name = Mary, salary = 5700,00]
 * [id = 1, name = Jack, salary = 6000,00]
 * [id = 10, name = Davis, salary = 6500,00]
 * [id = 4, name = Joe, salary = 7000,00]
 */

-> The Developer with smallest salary is removed first

Conclusion

We had learned how to work with Java PriorityQueue by examples:

  • Create Java PriorityQueue with Natural Ordering of Elements.
  • Create Java PriorityQueue with Custom Comparator.
  • Create Java PriorityQueue with Custom Object that implements Comparable interface.
  • Do a list operations of Java PriorityQueue: offer, peek, poll, remove...

Happy Learning! See you later!

52 thoughts on “How to use Java PriorityQueue with Examples”

  1. Hello there, You’ve done an incredible job. I will definitely digg it
    and personally suggest to my friends. I am confident they’ll be
    benefited from this web site.

  2. Howdy just wanted to give you a quick heads up. The text in your article seem to
    be running off the screen in Safari. I’m not sure if this is a format issue or something to do with internet browser
    compatibility but I figured I’d post to let you know.
    The layout look great though! Hope you get the problem solved soon. Cheers

  3. Hi there! I could have sworn I’ve been to this website before but after reading through some
    of the post I realized it’s new to me. Nonetheless,
    I’m definitely delighted I found it and I’ll be bookmarking and checking
    back frequently!

  4. I’m not sure where you’re getting your information, but good topic.
    I needs to spend some time learning much more or understanding more.
    Thanks for excellent information I was looking for this information for my mission.

  5. I’ve been browsing online more than 4 hours today, yet I never found
    any interesting article like yours. It’s pretty worth enough for me.
    In my view, if all site owners and bloggers made
    good content as you did, the internet will be a lot more useful than ever before.

  6. Thanks for any other fantastic article. The place else could anyone get that kind of
    information in such a perfect method of writing? I have a
    presentation subsequent week, and I am on the search for
    such information.

  7. I was suggested this web site through my cousin. I’m now not
    certain whether this publish is written by him as no one else know such precise about my trouble.
    You’re wonderful! Thanks!

  8. Definitely believe that which you said. Your favorite justification seemed to be
    on the web the easiest thing to be aware of. I say to you, I definitely get irked while people consider worries that they plainly don’t know about.
    You managed to hit the nail upon the top and also defined out the
    whole thing without having side-effects , people could take
    a signal. Will probably be back to get more. Thanks

  9. Hi there! This post could not be written any better! Readingthis post reminds me of my old room mate! He always kept talking about this.I will forward this page to him. Fairly certain he willhave a good read. Many thanks for sharing!

  10. Its such as you read my thoughts! You seem to
    grasp a lot approximately this, such as you wrote the book in it or something.
    I believe that you simply can do with some p.c. to power the message home a little bit, but other
    than that, that is great blog. An excellent read. I’ll certainly
    be back.

  11. Hello, I believe your website could be having web browser compatibility problems.When I look at your website in Safari, it looks fine however, when opening in IE, it’s got some overlapping issues.I just wanted to provide you with a quick headsup! Besides that, wonderful site!

  12. Your style is so unique in comparison to other people I have read stuff from.
    Thank you for posting when you have the opportunity, Guess I’ll just bookmark this blog.

  13. Hello, I think your website might be having browser compatibility issues.
    When I look at your blog site in Firefox, it looks fine but when opening in Internet
    Explorer, it has some overlapping. I just wanted to give you a
    quick heads up! Other then that, terrific
    blog!

  14. Hello, i read your blog from time to time and i own a similar one and i
    was just wondering if you get a lot of spam
    remarks? If so how do you stop it, any plugin or anything you can suggest?
    I get so much lately it’s driving me mad so any assistance is very much appreciated.

  15. Hi, i read your blog occasionally and i own a similar one andi was just curious if you get a lot of spam feedback? If so how do you stop it,any plugin or anything you can suggest? I get so much lately it’s driving meinsane so any support is very much appreciated.

  16. Hello There. I found your blog the use of msn. This is a really smartly written article.
    I will be sure to bookmark it and return to learn more of your useful information.
    Thanks for the post. I’ll certainly return.

  17. I was recommended this website by my cousin. I am not sure whether this post is written by him as
    nobody else know such detailed about my trouble. You are incredible!

    Thanks!

  18. you’re in reality a excellent webmaster. The site loading pace is amazing.
    It seems that you’re doing any unique trick. Also, The contents are
    masterpiece. you have done a excellent job on this matter!

  19. With havin so much content do you ever run into any problems of plagorism or copyright violation?
    My website has a lot of completely unique content I’ve either written myself or outsourced but it looks like
    a lot of it is popping it up all over the web without my authorization. Do
    you know any techniques to help stop content from being stolen? I’d genuinely appreciate it.

  20. Hey there this is kinda of off topic but I was wanting to know
    if blogs use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding experience
    so I wanted to get guidance from someone with experience.
    Any help would be greatly appreciated!

  21. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added
    I get several emails with the same comment.
    Is there any way you can remove me from that service?
    Thank you!

  22. Howdy! I know this is kinda off topic nevertheless I’d figured
    I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog post
    or vice-versa? My site covers a lot of the same topics as yours and I think
    we could greatly benefit from each other.
    If you’re interested feel free to send me an e-mail.
    I look forward to hearing from you! Excellent blog by the way!

  23. I every time used to read article in news papers but now as I am a user of internet sofrom now I am using net for content, thanks to web.

  24. What’s up i am kavin, its my first time to commenting anywhere,when i read this paragraph i thought i could also create comment due to this good paragraph.

  25. Whats up very cool blog!! Guy .. Beautiful .. Superb ..
    I’ll bookmark your blog and take the feeds also?
    I am glad to search out a lot of useful info right here within the publish, we
    want work out extra strategies in this regard, thank you for sharing.
    . . . . .

  26. Hello! I simply would like to offer you a big thumbs up for yourgreat information you have got here on this post.I am returning to your site for more soon.

  27. I know this website offers quality dependent articles or reviews and additional data, is there any other web page which provides such stuff
    in quality?

  28. Have you ever thought about writing an ebook
    or guest authoring on other sites? I have a blog based upon on the same information you
    discuss and would really like to have you share some stories/information. I know my viewers would value your
    work. If you’re even remotely interested, feel free to send me an e mail.

  29. Great items from you, man. I’ve take into accout your stuff
    previous to and you are just extremely magnificent.
    I actually like what you’ve acquired right here,
    really like what you’re stating and the way in which
    wherein you are saying it. You make it entertaining and you
    still take care of to stay it wise. I can not wait to read far more from
    you. This is really a tremendous web site.

  30. I was curious if you ever considered changing
    the layout of your site? Its very well written; I love what youve got
    to say. But maybe you could a little more in the way of
    content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 pictures.
    Maybe you could space it out better?

  31. I think this internet site has got some very wonderful information for everyone :D. “Years wrinkle the skin, but to give up enthusiasm wrinkles the soul.” by Samuel Ullman.

  32. I do not know if it’s just me or if everyone elseexperiencing issues with your blog. It appears as if some of the written text in your contentare running off the screen. Can somebody else please provide feedback and let meknow if this is happening to them as well? This could be a problemwith my web browser because I’ve had this happen before.Cheers

  33. I’m curious to find out what blog system you happen to be utilizing?
    I’m experiencing some small security issues with my latest blog and I’d like to find something more risk-free.

    Do you have any suggestions?

Leave a Reply

Your email address will not be published. Required fields are marked *