Tuesday, 13 March 2012

Replace all occurrences of specified element of Java ArrayList Example

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.ArrayList;
import java.util.Collections;
 
public class ReplaceAllArrayListExample {
 
  public static void main(String[] args) {
   
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to Arraylist
    arrayList.add("A");
    arrayList.add("B");
    arrayList.add("A");
    arrayList.add("C");
    arrayList.add("D");
 
    System.out.println("ArrayList Contains : " + arrayList);
   
    
    Collections.replaceAll(arrayList, "A","Replace All");
   
    System.out.println("After Replace All, ArrayList Contains : " + arrayList);
  }
}
 
/*
Output would be
ArrayList Contains : [A, B, A, C, D]
After Replace All, ArrayList Contains : [Replace All, B, Replace All, C, D]
*/

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...