How to Replace Specified Elements of ArrayList in Java


Here we will introduce a simple example to replace all occurrences of a specified element of ArrayList with replaceAll method of Collections class in Java.

Source Code

import java.util.ArrayList;
import java.util.Collections;


public class ReplaceOccurrencesElementsOfArraylist {

	
	public static void main(String[] args) {
		
		ArrayList al = new ArrayList();
		
		al.add("a");
		al.add("B");
		al.add("a");
		al.add("a");
		
		System.out.println("al:"+al);
		
		Collections.replaceAll(al, "a", "A");
		
		System.out.println("After the replacement:"+al);
	}

}

Output:

al:[a, B, a, a]
After the replacement:[A, B, A, A]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments