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 theArrayList
.operator
is a lambda expression or UnaryOperator that defines the transformation logic.
Parameters
Parameter | Description |
---|---|
operator | The 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 isnull
. - Any runtime exception thrown by the operator during iteration will be propagated to the caller.
- Throws
ConcurrentModificationException
if the list is structurally modified outside ofreplaceAll()
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
Aspect | Details |
---|---|
Method Purpose | Transform each element of an ArrayList using a function |
Syntax | list.replaceAll(UnaryOperator<E> operator) |
Parameters | operator (lambda or UnaryOperator for the transformation) |
Return Value | None (void ), modifies the list in-place |
Typical Use Cases | Bulk 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.