Replacing All Occurrences of Specified Element of Java ArrayList
ArrayList is present in java.util package and it is the implementation class of List interface. It does allow the duplicates elements and also it maintains the insertion order of the elements. It dynamically resized its capacity. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.
Example: In this program, we will first create an ArrayList of Integers and add elements using add() method, Now we will iterate over the ArrayList elements using the for each loop.
1 20 21 13 21 10 21
Approach(Using replaceAll() method)
In this program, we will create an ArrayList of Integers and add elements in it using add() method, then we will replace all occurrences of 21 with 200 using replaceAll() method.
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)).
1 20 200 13 200 10 200
Initial values are :[?, For, ?] Value after replace :[Geeks, For, Geeks]