Algorithms,  Collections,  Data Structures

Working with Queues in the Collections Framework

The queue data structure can be useful in algorithms where you need to process data in a sequential order. A queue contains the elements in the order they were added, that is, elements are inserted at the end and removed from the front, making it a FIFO – First In First Out data structure.

Standard queue operations

FunctionDescription
EnqueueAdds an item to the back
DequeueRemoves an item from the front
PeekAccesses the item at the front of the queue
    public static void main(String[] args) {
        Queue queue = new LinkedList<>();
        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(4);
        queue.add(5);
        System.out.println(queue);

        int removeItem = (int) queue.remove();
        System.out.println(removeItem);
        System.out.println("Remove item : " + queue.remove());
        System.out.println("Peek at queue : " + queue.peek());

        while(!queue.isEmpty()) {
            System.out.println("While not empty, remove another one : " + queue.remove());
        }
    }

Generate binary numbers using a Queue

//Using parsing
private static void generateBinaryNumbers(int i) {
        if (i < 0) {
            System.out.println();
            return;
        }
        Queue queue = new LinkedList();
        queue.add("1");
        for (int j = 0; j < i; j++) {
            int current = Integer.parseInt((String) queue.remove());
            System.out.println(current + " ");
            String s1 = current + "0";
            String s2 = current + "1";
            queue.add(s1);
            queue.add(s2);
        }
    }

    //Without using parsing - This is a more optimized solution
    private static void printBinary(int n) {
        if (n < 1) {
            System.out.println();
            return;
        }
        Queue<Integer> queue = new LinkedList<>();
        queue.add(1);
        for (int i = 0; i < n; i++) {
            int current = queue.remove();
            System.out.println(current + " ");
            queue.add(current * 10);
            queue.add(current * 10 + 1);
        }
    }

    //Test both methods
    public static void main(String[] args) {
        generateBinaryNumbers(10);
        printBinary(10);
    }