Collections public static boolean replaceAll(List list, T oldVal, T newVal) Method Example program


Replaces all occurrences of one specified value in a list with another.

Program

package com.candidjava;

import java.util.Collections;
import java.util.List;
import java.util.Vector;

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use Collections.replaceAll(List
 *              <T> list, T oldVal, T newVal) method.
 */
public class CollectionsReplaceAll {

	public static void main(String[] args) {
		List<String> vector = new Vector<String>();
		vector.add("karthik");
		vector.add("kamal");
		vector.add("moahn");
		vector.add("hari");
		vector.add("anand");
		vector.add("h");
		System.out.println("Initial values are :" + vector);
		Collections.replaceAll(vector, "h", "vinodh");
		System.out.println("Value after replace :" + vector);
	}
}

Output

Initial values are :[karthik, kamal, moahn, hari, anand, h]
Value after replace :[karthik, kamal, moahn, hari, anand, vinodh]

Explanation

public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal)
Replaces 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.)
Parameters:
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:
UnsupportedOperationException - if the specified list or its list-iterator does not support the set operation.
Since:
1.4


Related Post

Comments


©candidjava.com