Collections.replaceAll: In-Place Element Replacement
You'll learn how to replace all occurrences of a specific value with another value directly in a list using the Collections.replaceAll() method.
What Is Collections.replaceAll?
The Collections.replaceAll() method scans through a list and replaces every occurrence of one specified value with another value. Unlike creating a new list or manually looping through elements, this method modifies the original list in place, making it both convenient and efficient.
Think of it like a "find and replace" operation in a word processor—you tell it what to find and what to replace it with, and it updates the document directly.
How It Works
The method signature is:
static <T> boolean replaceAll(List<T> list, T oldVal, T newVal)
It returns true if at least one replacement was made, false otherwise. The method uses .equals() to match elements, so it works correctly with null values too.
Example Usage
List<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "apple", "cherry"));
Collections.replaceAll(fruits, "apple", "orange");
System.out.println(fruits); // [orange, banana, orange, cherry]
Both occurrences of "apple" were replaced with "orange" in the original list.
When to Use It
This method is perfect when you need to update multiple occurrences of a value throughout a list without creating a new collection or writing manual iteration logic. It's particularly useful for data normalization or batch updates.
Return Value Matters
boolean changed = Collections.replaceAll(list, "grape", "kiwi");
if (changed) {
System.out.println("At least one replacement was made");
}
Key Takeaway: Use Collections.replaceAll() to efficiently replace all occurrences of one value with another directly in a list, avoiding manual iteration and making your code more readable.