Skip to content

WebDevHubs

  • Home
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • Java
  • Selenium
  • PHP
  • Python
  • Programs
  • Toggle search form

Java ArrayList replaceAll() Method

Posted on July 24, 2025July 24, 2025 By Admin No Comments on Java ArrayList replaceAll() Method

The replaceAll() method is a convenient feature of the Java ArrayList class that allows you to transform all elements in a list using a given operation. This functional-style method is especially useful for applying a transformation, calculation, or bulk update to every item in the list without needing explicit loops. It was introduced in Java 8 and leverages Java’s lambda expressions and the UnaryOperator functional interface.

What Is the replaceAll() Method in ArrayList?

  • The replaceAll() method replaces each element of the list with the result of applying a given operation to that element.
  • The operation is specified by a lambda expression or a UnaryOperator—a special type of function that takes one input and returns one output of the same type.
  • The method is destructive: it modifies the original list in-place with the new values.

Syntax

public void replaceAll(UnaryOperator<E> operator)

Where:

  • E is the type of the elements in the ArrayList.
  • operator is a lambda expression or UnaryOperator that defines the transformation logic.

Parameters

ParameterDescription
operatorThe operation (lambda or UnaryOperator) to apply to each element.

Return Value

  • void – This method does not return a value. The original list is modified in place.

Exceptions

  • Throws NullPointerException if the specified operator is null.
  • Any runtime exception thrown by the operator during iteration will be propagated to the caller.
  • Throws ConcurrentModificationException if the list is structurally modified outside of replaceAll() while it’s running.

How Does replaceAll() Work Internally?

  • replaceAll() iterates over every element of the list and applies the operator to it.
  • The result of the operator replaces the original element in the same position of the list.
  • The size of the list remains unchanged.

Examples of the replaceAll() Method

1. Add 1 to Every Number in the List

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(9);
        numbers.add(8);
        numbers.add(6);
        numbers.add(1);

        numbers.replaceAll(n -> n + 1); // Add 1 to each number

        System.out.println(numbers); // Output: [6, 10, 9, 7, 2]
    }
}

This replaces each element with its value plus 11.

2. Convert All Strings to Uppercase

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> languages = new ArrayList<>();
        languages.add("java");
        languages.add("javascript");
        languages.add("swift");
        languages.add("python");

        languages.replaceAll(e -> e.toUpperCase());

        // Output: [JAVA, JAVASCRIPT, SWIFT, PYTHON]
        System.out.println(languages);
    }
}

Each string in the list is converted to uppercase.

3. Multiply All Elements by 2

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);

        numbers.replaceAll(e -> e * 2);

        System.out.println(numbers); // Output: [2, 4, 6]
    }
}

Every number is multiplied by 2.

4. Applying Conditional Logic

import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

        numbers.replaceAll(number -> (number % 2 == 0) ? number + 1 : number - 1);

        System.out.println(numbers); // Output: [0, 3, 2, 5, 4]
    }
}

Even numbers are incremented by 1, odd numbers are decremented by 1.

5. Custom UnaryOperator Implementation

import java.util.ArrayList;
import java.util.function.UnaryOperator;

class ToLowerCaseOperator implements UnaryOperator<String> {
    public String apply(String s) {
        return s.toLowerCase();
    }
}

public class CustomOperatorDemo {
    public static void main(String[] args) {
        ArrayList<String> items = new ArrayList<>();
        items.add("A");
        items.add("B");
        items.add("C");

        items.replaceAll(new ToLowerCaseOperator());

        System.out.println(items); // Output: [a, b, c]
    }
}

You can define complex logic in a dedicated class implementing UnaryOperator.

Important Notes

  • In-Place Modification: The list is changed directly; there is no copy returned.
  • Lambda Friendly: Works perfectly with lambda expressions for concise and readable code.
  • Type Consistency: The operator must return the same type as the list elements.
  • Performance: Suitable for bulk updates and cleaner than manual loops.
  • Not for Filtering: Use removeIf() for deleting elements—replaceAll() is for transforming values.
  • Exception Safety: Always ensure your operator handles nulls and expected edge cases to avoid runtime exceptions.

Summary

AspectDetails
Method PurposeTransform each element of an ArrayList using a function
Syntaxlist.replaceAll(UnaryOperator<E> operator)
Parametersoperator (lambda or UnaryOperator for the transformation)
Return ValueNone (void), modifies the list in-place
Typical Use CasesBulk updates, data normalization, formatting, calculations

Typical Use Cases

  • Batch data transformations: Update all items to a new format (e.g., lowercase, scaling numbers).
  • Cleanup before processing: Standardize list content before further actions.
  • Readability: Replace manual for-loops with expressive lambda-based transformations.
Java Tags:Java-ArrayList, Java-ArrayList-Method, Java-Collections

Post navigation

Previous Post: Java ArrayList removeIf() Method
Next Post: Java ArrayList retainAll() Method

Leave a Reply Cancel reply

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

  • Java ArrayList
  • Java ArrayList Methods
  • Java ArrayList add() Method
  • Java ArrayList addAll() Method
  • Java ArrayList clear() Method
  • Java ArrayList clone() Method
  • Java ArrayList contains() Method
  • Java ArrayList ensureCapacity() Method
  • Java ArrayList forEach() Method
  • Java ArrayList get() Method
  • Java ArrayList indexOf() Method
  • Java ArrayList isEmpty() Method
  • Java ArrayList iterator() Method
  • Java ArrayList lastIndexOf() Method
  • Java ArrayList listIterator() Method
  • Java ArrayList remove() Method
  • Java ArrayList removeAll() Method
  • Java ArrayList removeIf() Method
  • Java ArrayList replaceAll() Method
  • Java ArrayList retainAll() Method
  • Java ArrayList set() Method
  • Java ArrayList size() Method
  • Java ArrayList sort() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList subList() Method
  • Java ArrayList toArray() Method
  • Java ArrayList trimToSize() Method

Recent Posts

  • Java ArrayList trimToSize() Method
  • Java ArrayList toArray() Method
  • Java ArrayList subList() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList sort() Method

Recent Comments

No comments to show.

Important Pages

  • About Us
  • Contact Us
  • Terms of Use
  • Privacy Policy

Web Development

  • HTML
  • CSS
  • JavaScript
  • PHP

Programming Languages

  • Java
  • Python
  • PHP
  • Programs

Others

  • Selenium
  • Lodash
  • Java ArrayList
  • JavaScript Array Methods

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme