Java Collections replaceAll() Method
Example
Replace every "Volvo" in a list with "Mazda":
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Volvo");
cars.add("Ford");
System.out.println(Collections.replaceAll(cars, "Volvo", "Mazda"));
System.out.println(cars);
}
}
Definition and Usage
The replaceAll() method replaces every item in a list that is equal to oldVal with newVal.
Note: This is not the same as the replaceAll() method of a list, which changes every item with a lambda expression.
Syntax
public static boolean replaceAll(List<T> list, T oldVal, T newVal)
T refers to the data type of items in the list.
Parameter Values
| Parameter | Description |
|---|---|
| list | Required. The list to change. |
| oldVal | Required. The value to replace. |
| newVal | Required. The new value. |
Technical Details
| Returns: | true if at least one item was replaced, otherwise false. |
|---|
Related Pages
Java Collections Framework Tutorial
❮ Collections Methods