Java PriorityQueue retainAll() Method

The PriorityQueue class in Java provides the retainAll() method to retain only the elements in the queue that are contained in the specified collection.

Table of Contents

  1. Introduction
  2. retainAll Method Syntax
  3. Examples
    • Retaining Specific Elements in the PriorityQueue
    • Handling Elements Not in the Collection
  4. Real-World Use Case
    • Use Case: Task Management System
  5. Conclusion

Introduction

The PriorityQueue.retainAll(Collection<?> c) method is used to retain only those elements in the PriorityQueue that are contained in the specified collection. This method can be useful when you need to bulk retain a set of elements in the queue.

retainAll Method Syntax

The syntax for the retainAll method is as follows:

public boolean retainAll(Collection<?> c)
  • The method takes a single parameter c of type Collection<?>, which is the collection containing elements to be retained in the queue.
  • The method returns a boolean value: true if the queue was modified as a result of the call, false otherwise.

Examples

Retaining Specific Elements in the PriorityQueue

The retainAll method can be used to retain specific elements in a PriorityQueue that are present in a given collection.

Example

import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.Collection;

public class PriorityQueueRetainAllExample {
    public static void main(String[] args) {
        // Creating a PriorityQueue of Strings
        PriorityQueue<String> tasks = new PriorityQueue<>();

        // Adding elements to the PriorityQueue
        tasks.add("Complete project report");
        tasks.add("Email client updates");
        tasks.add("Prepare presentation");

        // Creating a collection of tasks to retain
        Collection<String> tasksToRetain = new ArrayList<>();
        tasksToRetain.add("Email client updates");
        tasksToRetain.add("Prepare presentation");

        // Retaining specific elements in the PriorityQueue
        boolean isRetained = tasks.retainAll(tasksToRetain);

        // Printing the result of the retainAll operation
        System.out.println("Were tasks retained? " + isRetained);

        // Printing the PriorityQueue after retainAll
        System.out.println("PriorityQueue after retainAll: " + tasks);
    }
}

Output:

Were tasks retained? true
PriorityQueue after retainAll: [Email client updates, Prepare presentation]

Handling Elements Not in the Collection

When the elements in the specified collection are not present in the PriorityQueue, the retainAll method will remove all elements from the queue except those that are specified.

Example

import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.Collection;

public class NonExistentElementsRetainAllExample {
    public static void main(String[] args) {
        // Creating a PriorityQueue of Strings
        PriorityQueue<String> tasks = new PriorityQueue<>();

        // Adding elements to the PriorityQueue
        tasks.add("Complete project report");
        tasks.add("Email client updates");

        // Creating a collection of tasks to retain that do not exist in the PriorityQueue
        Collection<String> tasksToRetain = new ArrayList<>();
        tasksToRetain.add("Non-existent task");

        // Retaining specific elements in the PriorityQueue
        boolean isRetained = tasks.retainAll(tasksToRetain);

        // Printing the result of the retainAll operation
        System.out.println("Were tasks retained? " + isRetained);

        // Printing the PriorityQueue after retainAll
        System.out.println("PriorityQueue after retainAll: " + tasks);
    }
}

Output:

Were tasks retained? true
PriorityQueue after retainAll: []

Real-World Use Case

Use Case: Task Management System

In a task management system, you may need to retain a group of tasks in the queue, such as when a batch of tasks needs to be prioritized or processed together. The retainAll method can help achieve this functionality efficiently.

Example

import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.Collection;

public class TaskManagementSystem {
    public static void main(String[] args) {
        // Creating a PriorityQueue to store tasks
        PriorityQueue<Task> tasks = new PriorityQueue<>();

        // Adding initial tasks with different priorities
        tasks.add(new Task("Complete project report", 2));
        tasks.add(new Task("Email client updates", 1));
        tasks.add(new Task("Prepare presentation", 3));

        // Creating a collection of tasks to retain
        Collection<Task> tasksToRetain = new ArrayList<>();
        tasksToRetain.add(new Task("Email client updates", 1));
        tasksToRetain.add(new Task("Prepare presentation", 3));

        // Retaining specific tasks in the PriorityQueue
        boolean isRetained = tasks.retainAll(tasksToRetain);

        // Printing the result of the retainAll operation
        System.out.println("Were tasks retained? " + isRetained);

        // Printing the PriorityQueue after retainAll
        System.out.println("PriorityQueue after retainAll: " + tasks);
    }
}

class Task implements Comparable<Task> {
    private String description;
    private int priority;

    public Task(String description, int priority) {
        this.description = description;
        this.priority = priority;
    }

    public String getDescription() {
        return description;
    }

    public int getPriority() {
        return priority;
    }

    @Override
    public int compareTo(Task other) {
        return Integer.compare(this.priority, other.priority);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Task task = (Task) o;

        if (priority != task.priority) return false;
        return description != null ? description.equals(task.description) : task.description == null;
    }

    @Override
    public int hashCode() {
        int result = description != null ? description.hashCode() : 0;
        result = 31 * result + priority;
        return result;
    }

    @Override
    public String toString() {
        return description + " (Priority: " + priority + ")";
    }
}

Output:

Were tasks retained? true
PriorityQueue after retainAll: [Email client updates (Priority: 1), Prepare presentation (Priority: 3)]

Conclusion

The PriorityQueue.retainAll(Collection<?> c) method in Java is used for retaining specific elements in a priority queue based on a given collection. Understanding how to use this method allows you to efficiently manage and manipulate elements in the queue, making it particularly useful in applications like task management systems where you need to retain multiple tasks based on certain conditions.

Comments