31 janeiro 2018

How to use Queue in Java


public class QueueDemo {

    public static void main(String args[]) {
        Queue months = new LinkedList<>();
        // Example 1 - Adding objects into Queue
        System.out.println("Queue : " + months);
        months.add("JAN");
        months.add("FEB");
        months.add("MAR");
        months.add("APR");
        months.add("MAY");
        months.add("JUN");
        months.add("JUL");
        months.add("AUG");
        months.add("SEP");
        months.add("OCT");
        months.add("NOV");
        months.add("DEC");
        System.out.println("Queue after initialization : " + months);

        // Example 2 - Checking if an Object is in Queue or not
        boolean hasMay = months.contains("MAY");
        System.out.println("Does Queue has MAY in it? " + hasMay);

        // Example 3 - Retrieving value from head of Queue
        String head = months.peek();
        System.out.println("Head of the Queue contains : " + head);

        // Example 4 - Removing objects from head of the Queue
        String oldHead = months.poll();
        String newHead = months.peek();
        System.out.println("old head : " + oldHead);
        System.out.println("new head : " + newHead);

        // Example 5 - Another way to remove head objects from Queue
        months.remove();
        System.out.println("now head of Queue is: " + months.peek());
    }
}


Source: java67.com

Sem comentários: