Replace all occurrences of specified element of ArrayList with Java Collections


In order to replace all occurrences of specified element of ArrayList with Java Collections, we use the Collections.replaceAll() method. This method returns true if list contains one or more elements e such that (oldVal==null ? e==null : oldVal.equals(e)).

Declaration −The java.util.Collections.replaceAll() is declared as follows −

public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal)

where oldVal is the element value in the list to be replaced, newVal is the element value with which it is replaced and list is the list in which replacement takes place.

Let us see a program to replace all occurrences of specified element of ArrayList with Java Collections −

Example

 Live Demo

import java.util.*;
public class Example {
   public static void main (String[] args) {
      ArrayList<Integer> list = new ArrayList<Integer>();
      list.add(1);
      list.add(2);
      list.add(7);
      list.add(1);
      list.add(3);
      list.add(1);
      System.out.println("Original list : " + list);
      Collections.replaceAll(list,1,4); // replacing elements with value 1 with value 4
      System.out.println("New list : " + list);
   }
}

Output

Original list : [1, 2, 7, 1, 3, 1]
New list : [4, 2, 7, 4, 3, 4]

Updated on: 25-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements