tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collections > Collection Replace

Collection Replace 

The following example shows how to use Collections.replaceAll API. It replaces all occurrences of one specified value in a list with another.

File Name  :  
com/bethecoder/tutorials/utils/collections/CollectionsReplace.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsReplace {

  public static void main (String [] args) {
    
    List<Integer> intList = Arrays.asList(new Integer [] {
        1234
        123,
        12,
        1
    });
    
    System.out.println("Initial list : " + intList);
    
    Collections.replaceAll(intList, 1, -1);
    System.out.println("After replace : " + intList);
    
  }
}
   

It gives the following output,
Initial list : [1, 2, 3, 4, 1, 2, 3, 1, 2, 1]
After replace : [-1, 2, 3, 4, -1, 2, 3, -1, 2, -1]



 
  


  
bl  br