Java ArrayList replaceAll() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
ArrayList

Definition

In Java 8 and later, replaceAll(operator) replaces every element of an ArrayList with the result of applying a function to it. The function is a UnaryOperator<E>: it takes one element and returns a value of the same type.

The list is changed in place: the size and the positions stay the same, only the values change. It is a shorter form of a loop that calls set(i, f(get(i))). Do not confuse it with String.replaceAll, which replaces text using a regular expression.

An instance method of java.util.ArrayList (Java 1.2+): a resizable-array list with index access that allows null and duplicates and is not thread-safe. replaceAll was added in Java 8 as a default method of List; ArrayList overrides it with the same behavior.

Syntax

Pass a lambda or method reference that maps an element to its new value.

Java
List<String> list = new ArrayList<>(Arrays.asList("a", "b"));
list.replaceAll(s -> s.toUpperCase());      // [A, B]
list.replaceAll(String::toLowerCase);       // [a, b]
CallWhat it does
list.replaceAll(x -> ...)A lambda computes each new value.
list.replaceAll(String::trim)A method reference for String lists.
list.replaceAll(n -> n * 2)Doubles every number in a List<Integer>.
Collections.replaceAll(list, oldVal, newVal)A different method: swaps one value for another everywhere.

The operator runs once per element, from index 0 to the end. Its result must have the list's element type: for a List<String>, the operator must return a String.

Library declarations
Java
// java.util.ArrayList<E>
public void replaceAll(UnaryOperator<E> operator)

// Declared in List<E> (default method since Java 8)

// java.util.function.UnaryOperator<T> extends Function<T, T>
T apply(T t)

Parameters

ParameterDescription
operator (UnaryOperator<E>)The function applied to each element. Must not be null.

Return Value

Return ValueDescription
voidNothing is returned; the list itself is updated.

Compare with Similar Methods

Other whole-list operations:

MethodHow it differs
set(i, e)Replaces a single element.
forEach(action)Visits each element but cannot replace it.
removeIf(filter)Removes elements instead of changing them.
sort(c)Reorders elements instead of changing their values.

Java Examples

Example 1 — Uppercase Every Name, Then Keep Initials

Use a method reference, then a lambda, to transform every name in place.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListReplaceAllDemo {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(Arrays.asList("ada", "linus", "grace"));

        names.replaceAll(String::toUpperCase);
        System.out.println(names);

        names.replaceAll(n -> n.charAt(0) + ".");
        System.out.println(names);
    }
}

How It Works

  1. Method reference. String::toUpperCase is shorthand for n -> n.toUpperCase(), applied to each name.
  2. In place. The same list object now holds the uppercase strings; no second list was created.
  3. Lambda version. The second call keeps only the first letter of each name and adds a dot.
  4. Type stays String. A char plus a String produces a String, so the lambda fits UnaryOperator<String>.

Example 2 — Apply a Discount to Every Price

Take 10% off every price with integer math, then cap prices at 100.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListReplaceAllPrices {
    public static void main(String[] args) {
        List<Integer> prices = new ArrayList<>(Arrays.asList(100, 250, 40));

        prices.replaceAll(p -> p - p / 10);
        System.out.println("10% off: " + prices);

        prices.replaceAll(p -> p > 100 ? 100 : p);
        System.out.println("capped:  " + prices);
    }
}

How It Works

  1. Integer division. p / 10 drops any remainder, so the discounts are 10, 25, and 4.
  2. New prices. Subtracting them gives 90, 225, and 36, written back to the same positions.
  3. Conditional replace. The second lambda caps anything above 100, so only 225 changes.
  4. A value for every element. Prices that should stay the same are returned unchanged as p, because replaceAll always writes a result back.

Example 3 — replaceAll() vs a set() Loop, and a null Operator

Trim two copies of a list in two different ways, compare them, then pass null.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.UnaryOperator;

public class ArrayListReplaceAllVsLoop {
    public static void main(String[] args) {
        UnaryOperator<String> trim = s -> s.trim();
        List<String> a = new ArrayList<>(Arrays.asList(" tea ", "coffee ", " milk"));
        List<String> b = new ArrayList<>(a);

        a.replaceAll(trim);
        for (int i = 0; i < b.size(); i++) {
            b.set(i, trim.apply(b.get(i)));
        }
        System.out.println(a + " " + a.equals(b));

        try {
            a.replaceAll(null);
        } catch (NullPointerException e) {
            System.out.println("replaceAll(null): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. A named operator. trim is a UnaryOperator<String> variable, so the same function can be used in both versions.
  2. Two ways. a uses replaceAll(trim); b uses a classic loop with get, apply, and set.
  3. Same result. Both lists end up as [tea, coffee, milk], so equals returns true.
  4. No operator. Passing null throws NullPointerException before any element is touched.

Frequently Asked Questions

It applies a function to every element and stores each result back at the same index, changing the list in place.
Java 8, together with lambdas and the java.util.function interfaces such as UnaryOperator.
No. String.replaceAll replaces text that matches a regular expression. List.replaceAll transforms each element of a list with a function.
No. The operator must return the same type as the list. To build a list of another type, use list.stream().map(...) and collect into a new list.
No. Its return type is void and it updates the existing list.

Next: retainAll()

Keep only elements found in another collection.

retainAll() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful