The replaceAll() method of java.util.Collections class is used to Replaces all occurrences of one specified value in a list with another. More formally, replaces with newVal each element e in list such that (oldVal==null ? e==null : oldVal.equals(e)). (This method has no effect on the size of the list.)
Let’s consider the following vector:
Now in this vector we have to replace all occurrences of 5 with a given value. Let’s say the value here is -1. After replacing our vector should become as shown below:
A naive way to approach this problem is to traverse the entire vector and while traversal if the element in vector is equal the specified element then replace it with the given value.
However, in Java, we have a Built-in method replaceAll() as a part of Java Collections which does the same.
public static boolean replaceAll(List list, T oldVal, T newVal)
Parameters: This method takes the following argument as a Parameter
- list – the list in which replacement is to occur.
- oldVal – the old value to be replaced.
- newVal – the new value with which oldVal is to be replaced.
Return Value: This method returns true if list contained one or more elements e such that (oldVal==null ? e==null : oldVal.equals(e)).
Vector before Replacing is: [5, 6, 8, 5, 9, 1, 5, 2] Vector after Replacing is: [-1, 6, 8, -1, 9, 1, -1, 2]
Now let’s consider a Vector having String instead of Integer values:
Now in this vector, we have to replace all occurrences of CAT with a given String. Let’s say the string here is LION. After replacing our vector should become as shown below:
Vector before Replacing is: [CAT, DOG, CAT, HORSE, TIGER, CAT] Vector after Replacing is: [LION, DOG, LION, HORSE, TIGER, LION]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.