Home Blog Java Notes

Java PriorityQueue Example

Published:


class Book implements Comparable{
    int id;
    String name,author,publisher;
    int quantity;
    public Book(int id, String name, String author, String publisher, int quantity) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.publisher = publisher;
        this.quantity = quantity;
    }
    public int compareTo(Book b) {
        if(id>b.id){
            return 1;
        }else if(id queue = new PriorityQueue();
        //Creating Books
        Book b1 = new Book(121, "Let us C", "Yashwant Kanetkar", "BPB", 8);
        Book b2 = new Book(233, "Operating System", "Galvin", "Wiley", 6);
        Book b3 = new Book(101, "Data Communications & Networking", "Forouzan", "Mc Graw Hill", 4);
        Book b4 = new Book(121, "Operating System 2", "Galvin", "Wiley", 6);
        //Adding Books to the queue
        queue.add(b1);
        queue.add(b2);
        queue.add(b3);
        queue.add(b4);

        System.out.println("Traversing the queue elements:");
        //Traversing queue elements
        for (Book b : queue) {
            System.out.println(b.id + " " + b.name + " " + b.author + " " + b.publisher + " " + b.quantity);
        }
        queue.remove();
        System.out.println("After removing one book record:");
        for (Book b : queue) {
            System.out.println(b.id + " " + b.name + " " + b.author + " " + b.publisher + " " + b.quantity);
        }

    }

}
--Output
Traversing the queue elements:
101 Data Communications & Networking Forouzan Mc Graw Hill 4
121 Operating System 2 Galvin Wiley 6
121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6
After removing one book record:
121 Operating System 2 Galvin Wiley 6
233 Operating System Galvin Wiley 6
121 Let us C Yashwant Kanetkar BPB 8
Comment