Following example shows how to replace all the occurrence of element with another element using Collections.replaceAll(list, oldVal, newVal) method in Java.
<String> boolean java.util.Collections.replaceAll(List<String> list, String oldVal, String newVal)
replaceAll
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.
Sample Program
ReplaceElementInList.java
Result
The above code will produce the following output.
<String> boolean java.util.Collections.replaceAll(List<String> list, String oldVal, String newVal)
replaceAll
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.
Sample Program
ReplaceElementInList.java
package com.javatutorialcorner.collection; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ReplaceElementInList { public static void main(String[] args) { String[] nameArray = new String[] { "Spring", "Struts", "Hibernate", "Webservice", "SOAP Webservice", "RESTful Webservice" }; List<String> nameList = Arrays.asList(nameArray); System.out.println("*********** Before Replace ************"); for (String name : nameList) { System.out.println(name); } System.out.println("*********** After Replace ************"); Collections.replaceAll(nameList, "Spring", "Spring Framework"); for (String name : nameList) { System.out.println(name); } } }
Result
The above code will produce the following output.
*********** Before Replace ************
Spring
Struts
Hibernate
Webservice
SOAP Webservice
RESTful Webservice
*********** After Replace ************
Spring Framework
Struts
Hibernate
Webservice
SOAP Webservice
RESTful Webservice
0 comments:
Post a Comment