WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Java Collections Β· Guru Β· question 90 of 100

How do you implement a custom Queue in Java Collections that supports efficient merging of queues, and what are some use cases for doing so?

πŸ“• Buy this interview preparation book: 100 Java Collections questions & answers β€” PDF + EPUB for $5

To implement a custom Queue in Java Collections that supports efficient merging of queues, we can create a subclass of the Queue interface and implement the necessary methods.

Here is an example implementation of a custom Queue called "MergingQueue":

import java.util.LinkedList;
import java.util.Queue;

public class MergingQueue<T> implements Queue<T> {
    private final LinkedList<T> list = new LinkedList<>();

    @Override
    public boolean add(T t) {
        return list.add(t);
    }

    @Override
    public boolean offer(T t) {
        return list.offer(t);
    }

    @Override
    public T remove() {
        return list.remove();
    }

    @Override
    public T poll() {
        return list.poll();
    }

    @Override
    public T element() {
        return list.element();
    }

    @Override
    public T peek() {
        return list.peek();
    }

    public void merge(MergingQueue<? extends T> otherQueue) {
        list.addAll(otherQueue.list);
    }
}

In this implementation, we extend the Queue interface and use a LinkedList to store the elements of the queue. We then implement the necessary methods for the Queue interface, such as add, offer, remove, poll, element, and peek.

We also add a custom method called "merge" that takes another MergingQueue as a parameter and adds all the elements of the other queue to this queue using the addAll method of the underlying LinkedList.

One use case for a merging queue is in multi-threaded applications where different threads produce data that needs to be processed in order. Each thread can add its data to a separate merging queue, and the data can be merged and processed in the order they were added. This allows for efficient merging of data from multiple sources while preserving the order of the data.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview β€” then scores it.
πŸ“ž Practice Java Collections β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Java Collections questions & answers β€” PDF + EPUB for $5

All 100 Java Collections questions Β· All topics