Java Examples - Replace an element in a list
Problem Description:
How to replace an element in a list
Solution:
Following example uses replaceAll() method to replace all the
occurance of an element with a different element in a list.
import java.util.*;
public class Main {
public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six
one three Four".split(" "));
System.out.println("List :"+list);
Collections.replaceAll(list, "one", "hundread");
System.out.println("replaceAll: " + list);
}
}
Result:
The above code sample will produce the following result.
List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundread, Two, three, Four, five, six,
hundread, three, Four]