Search code examples
javaqueuecomparatorpriority-queue

How to Print PriorityQueue with Custom Object in Java


I want to print PriorityQueue of custom object. But when i see any official docs and tutorial, i have to use poll method. Is there any way i can print without removing the element? Here is my code:

Data class:

class Mhswa {

    String nama;
    int thnMasuk;

    public Mhswa(String nama, int thnMasuk) {
        this.nama = nama;
        this.thnMasuk = thnMasuk;
    }

    public String getNama() {
        return nama;
    }
}

Comparator class:

class MhswaCompare implements Comparator<Mhswa> {
    public int compare(Mhswa s1, Mhswa s2) {
        if (s1.thnMasuk < s2.thnMasuk)
            return -1;
        else if (s1.thnMasuk > s2.thnMasuk)
            return 1;
        return 0;
    }
}

Main class:

public static void main(String[] args) {
        PriorityQueue<Mhswa> pq = new PriorityQueue<>(5, new MhswaCompare());
        pq.add(new Mhswa("Sandman", 2019));
        pq.add(new Mhswa("Ironman", 2020));
        pq.add(new Mhswa("Iceman", 2021));
        pq.add(new Mhswa("Landman", 2018));
        pq.add(new Mhswa("Wingman", 2010));
        pq.add(new Mhswa("Catman", 2019));
        pq.add(new Mhswa("Speedman", 2015));

        int i = 0;
        // the print section that have to use poll()
        while (!pq.isEmpty()) { 
            System.out.println("Data ke " + i + " : " + pq.peek().nama + " " + pq.peek().thnMasuk);
            pq.poll();
            i++;
        }

    }
}

Thanks for the help.


Solution

  • You could use an Iterator since PriorityQueue implements Iterable:

    Iterator it = pq.iterator();
    while (it.hasNext()) { 
        Mhswa value = it.next();
        System.out.println("Data ke " + i + " : " + value.nama + " " + value.thnMasuk);
        i++;
    }