Java Collections replaceAll() Method

The replaceAll() method in Java is a utility method provided by the java.util.Collections class. It is used to replace all occurrences of a specified value in a list with another value. This method is useful for updating the elements of a list when you need to change all instances of a particular value to a new value.

Table of Contents

  1. Introduction
  2. replaceAll() Method Syntax
  3. Examples
    • Basic Usage of replaceAll()
    • Using replaceAll() with Custom Classes
  4. Real-World Use Case
  5. Conclusion

Introduction

The Collections.replaceAll() method is used to iterate over a list and replace all occurrences of a specified element with another element. This operation modifies the list in place, meaning that the original list is directly altered. The method returns a boolean indicating whether any replacements were made.

replaceAll() Method Syntax

The syntax for the replaceAll() method is as follows:

public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal)

Parameters:

  • list: The list in which to replace occurrences of the specified value.
  • oldVal: The value to be replaced in the list.
  • newVal: The value to replace all occurrences of oldVal.

Returns:

  • true if one or more elements were replaced; false otherwise.

Throws:

  • UnsupportedOperationException if the list does not support the set operation.
  • NullPointerException if the list is null.

Examples

Basic Usage of replaceAll()

The following example demonstrates how to use the replaceAll() method to replace all occurrences of a specified value in a list with another value.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ReplaceAllExample {
    public static void main(String[] args) {
        // Create a list with initial elements
        List<String> fruits = new ArrayList<>();
        Collections.addAll(fruits, "Apple", "Banana", "Apple", "Cherry", "Apple");

        // Display the original list
        System.out.println("Original List: " + fruits);

        // Use the replaceAll() method to replace "Apple" with "Mango"
        boolean replaced = Collections.replaceAll(fruits, "Apple", "Mango");

        // Display the modified list and whether replacements were made
        System.out.println("Modified List: " + fruits);
        System.out.println("Were replacements made? " + replaced);
    }
}

Output:

Original List: [Apple, Banana, Apple, Cherry, Apple]
Modified List: [Mango, Banana, Mango, Cherry, Mango]
Were replacements made? true

Using replaceAll() with Custom Classes

You can also use the replaceAll() method with lists containing instances of custom classes.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Student {
    String name;

    Student(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Student student = (Student) obj;
        return name.equals(student.name);
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }

    @Override
    public String toString() {
        return name;
    }
}

public class CustomReplaceAllExample {
    public static void main(String[] args) {
        // Create a list of students
        List<Student> students = new ArrayList<>();
        students.add(new Student("Amit"));
        students.add(new Student("Neha"));
        students.add(new Student("Amit"));
        students.add(new Student("Raj"));

        // Display the original student list
        System.out.println("Original Student List: " + students);

        // Use the replaceAll() method to replace "Amit" with "Vikram"
        boolean replaced = Collections.replaceAll(students, new Student("Amit"), new Student("Vikram"));

        // Display the modified student list and whether replacements were made
        System.out.println("Modified Student List: " + students);
        System.out.println("Were replacements made? " + replaced);
    }
}

Output:

Original Student List: [Amit, Neha, Amit, Raj]
Modified Student List: [Vikram, Neha, Vikram, Raj]
Were replacements made? true

Explanation:

  1. Original List: The list contains multiple occurrences of the specified element, which need to be replaced.

  2. Replacement: The replaceAll() method is used to replace all instances of oldVal with newVal, demonstrating its utility with both simple data types and custom classes.

  3. Equality Check: The equals() method is overridden in the custom class to ensure that the comparison is based on the name field, allowing for accurate replacements.

Real-World Use Case

Updating Product Prices in a List

In real-world applications, the replaceAll() method can be used to update the prices of products in a list, replacing outdated prices with new ones.

Example

Imagine a scenario where you need to update the price of a product in a list of products.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Product {
    String name;
    double price;

    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Product product = (Product) obj;
        return Double.compare(product.price, price) == 0 && name.equals(product.name);
    }

    @Override
    public int hashCode() {
        return name.hashCode() + Double.hashCode(price);
    }

    @Override
    public String toString() {
        return name + " ($" + price + ")";
    }
}

public class ProductPriceUpdateExample {
    public static void main(String[] args) {
        // Create a list of products
        List<Product> products = new ArrayList<>();
        products.add(new Product("Laptop", 1200.00));
        products.add(new Product("Smartphone", 800.00));
        products.add(new Product("Laptop", 1200.00));
        products.add(new Product("Tablet", 500.00));

        // Display the original product list
        System.out.println("Original Product List: " + products);

        // Use the replaceAll() method to update the price of "Laptop"
        boolean replaced = Collections.replaceAll(products, new Product("Laptop", 1200.00), new Product("Laptop", 1100.00));

        // Display the modified product list and whether replacements were made
        System.out.println("Modified Product List: " + products);
        System.out.println("Were replacements made? " + replaced);
    }
}

Output:

Original Product List: [Laptop ($1200.0), Smartphone ($800.0), Laptop ($1200.0), Tablet ($500.0)]
Modified Product List: [Laptop ($1100.0), Smartphone ($800.0), Laptop ($1100.0), Tablet ($500.0)]
Were replacements made? true

Explanation:

  1. Product List: The list contains products with specific names and prices.

  2. Price Update: The replaceAll() method is used to update the price of "Laptop" from $1200.00 to $1100.00, demonstrating its utility in modifying list elements.

  3. Equality Check: The equals() method is overridden to ensure that both name and price are compared for accurate replacements.

Conclusion

The Collections.replaceAll() method is a powerful utility for replacing occurrences of a specified element in a list with another element in Java. By providing a simple way to update list elements, it enhances the flexibility and readability of your code. This method is particularly valuable in scenarios where you need to modify list contents efficiently, improving the robustness and maintainability of your Java applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top