Java Utility Library

Java Collections - replaceAll() Method



The java.util.Collections.replaceAll() method is used to replace all occurrences of one specified value in a list with another.

Syntax

public static <T> boolean replaceAll(List<T> list,
                                     T oldVal,
                                     T newVal)

Here, T is the type of element in the list.


Parameters

list Specify the list in which replacement is to occur.
oldVal Specify the old value to be replaced.
newVal Specify the new value with which oldVal is to be replaced.

Return Value

Returns true if list contained one or more elements e such that (oldVal==null ? e==null : oldVal.equals(e)).

Exception

Throws UnsupportedOperationException, if the specified list or its list-iterator does not support the set operation.

Example:

In the example below, the java.util.Collections.replaceAll() method is used to replace all occurrences of specified element with new element in the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a list objects
    List<Integer> MyList = new ArrayList<Integer>();

    //populating MyList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(10);
    MyList.add(10);
    MyList.add(10);
    MyList.add(60);

    //printing the MyList
    System.out.println("MyList contains: " + MyList); 

    //replacing all occurrences of 10 with 25
    Collections.replaceAll(MyList, 10, 25);

    //printing the MyList
    System.out.println("MyList contains: " + MyList); 
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30, 10, 10, 10, 60]
MyList contains: [25, 20, 30, 25, 25, 25, 60]

❮ Java.util - Collections