Replacing all occurrences of one specified value in a list with another

Replacing 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.)



package collection.demos;



import java.util.ArrayList;

import java.util.Collections;

public class ReplacingElementsInList {

 public static void main(String[] args) {

        ArrayList<String> items=new ArrayList<String>();

        items.add("A");

        items.add("B");

        items.add("C");

        items.add("D");

        items.add("E");

        System.out.println("Initial Elements  : "+items);

        Collections.replaceAll(items, "C","F");

        System.out.println("After replaced    : "+items);

    }

}

/*

 * OUTPUT :

  Initial Elements  : [A, B, C, D, E]

  After replaced    : [A, B, F, D, E]

 */

No comments:

Popular Posts