The replaceAll() method of java.util.Collections class is used to replace all occurrences of one specified value in a list with another. More formally, replaces with newVal each element e in the list such that
oldVal == null ? e==null : oldVal.equals(e)
Note: This method has no effect on the size of the list.
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 the list contained one or more elements e such that as shown below else false
oldVal== null ? e==null : oldVal.equals(e)
Syntax:
public static boolean replaceAll(List list, T oldVal, T newVal)
Example 1:
Java
import java.util.*;
public class GFG {
public static void main(String[] argv) throws Exception
{
try {
List<String> vector = new Vector<String>();
vector.add( "A" );
vector.add( "B" );
vector.add( "A" );
vector.add( "C" );
System.out.println( "Initial Vector :" + vector);
Collections.replaceAll(vector, "A" , "TAJMAHAL" );
System.out.println( "Vector after replace :"
+ vector);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output
Initial Vector :[A, B, A, C]
Vector after replace :[TAJMAHAL, B, TAJMAHAL, C]
Example 2:
Java
import java.util.*;
public class GFG {
public static void main(String[] argv) throws Exception
{
try {
List<Integer> vector = new Vector<Integer>();
vector.add( 20 );
vector.add( 30 );
vector.add( 20 );
vector.add( 30 );
System.out.println( "Initial values are :"
+ vector);
Collections.replaceAll(vector, 20 , 400 );
System.out.println( "Value after replace :"
+ vector);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Initial values are :[20, 30, 20, 30]
Value after replace :[400, 30, 400, 30]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
22 Apr, 2022
Like Article
Save Article