Collections.replaceAll(List, E, E) in Java

Collections.replaceAll(List, E, E): This method is available in java.util.Collections class of Java.

Syntax:

<E> boolean java.util.Collections.replaceAll(List<E> list, E oldVal, E newVal)

This method takes three arguments. This method replaces all occurrences of one specified value in a list with another.

Parameters: Three parameters are required for this method.

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.

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

Throws:

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

Approach

Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsreplaceAll {
    public static void main(String[] args) {

        List<Integer> arrlist = new ArrayList<Integer>();

        arrlist.add(12);
        arrlist.add(12);
        arrlist.add(10);
        arrlist.add(36);
        arrlist.add(12);

        System.out.println("Before replace: " + arrlist);

        Integer oldValue = 12, newValue = 5;
        Collections.replaceAll(arrlist, oldValue, newValue);

        System.out.println("After replace: " + arrlist);

    }
}

Output:

Before replace: [12, 12, 10, 36, 12]

After replace: [5, 5, 10, 36, 5]


No comments:

Post a Comment