This example shows how to replace all occurrences of one element in java with another using the replaceAll() of the Collections class. More formally, the method replaceAll() replaces each o object in object collections that implement the java.util.List (Vector, ArrayList, LinkedList) so that oldVal==null? o==null : ancienVal.equals(o).
public static < T> boolean replaceAll(List< T> list,
T ancienVal,
T newVal)
This method revises true if the list contains at least one instance that has been overridden.
Java doc: the replaceAll() method of the Collections
import java.util.ArrayList;Run:
import java.util.Collections;
import java.util.List;
public class ArrayListReplaceAll {
public static void main(String[] args) {
// Create an ArrayList< String>
ArrayList< String> aList = new ArrayList< String> ();
//add string
aList.add("a");
aList.add("b");
aList.add("a");
aList.add("c");
aList.add("d");
aList.add("e");
aList.add("a");
System.out.println("Before");
for(String e:aList)
System.out.println(e);
//replace all occurrences of 'a' with 'aa'
Collections.replaceAll(aList, "a", "aa");
System.out.println("After");
for(String e:aList)
System.out.println(e);
}
}
BeforeReferences:
a
b
a
c
d
e
a
After
aa
b
aa
c< br />d
e
aa
Java doc: the replaceAll() method of the Collections
Commentaires (0)
Laisser un commentaire
Connectez-vous pour commenter
Rejoignez la discussion et partagez vos connaissances avec la communauté
Chargement des commentaires...