Home  >  Core Java

Collections.replaceAll in Java

By Arvind Rai, June 27, 2022
On this page we will learn using Collections.replaceAll method.
1. The replaceAll is a static method of java.util.Collections class.
2. The Collections.replaceAll replaces all occurrences of a specified value from the given value in a list.
3. Find the method declaration.
static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) 
Replaces with newVal each element e in list such that
(oldVal==null ? e==null : oldVal.equals(e)) 

Type Parameters:
T is the class of the objects in the list.

Parameters:
The list is the list in which replacement is to occur.
The oldVal is the old value to be replaced.
The newVal is the new value with which oldVal is to be replaced.

Returns: Returns true if list contained one or more elements e such that
(oldVal==null ? e==null : oldVal.equals(e)) 

Throws: If the specified list does not support operation, method throws UnsupportedOperationException.



Example-1

List<String> list = new ArrayList<>();
list.add("Mahesh");
list.add("Suresh");
list.add("Mahesh");
String oldVal = "Mahesh";
String newVal = "Shiva";
Collections.replaceAll(list, oldVal, newVal);
System.out.println(list); 
Output
[Shiva, Suresh, Shiva] 

Example-2

List<Integer> list = new ArrayList<>();
list.add(20);
list.add(15);
list.add(20);
int oldVal = 20;
int newVal = 30;
Collections.replaceAll(list, oldVal, newVal);
System.out.println(list); 
Output
[30, 15, 30] 

Example-3

List<Integer> list = new ArrayList<>();
list.add(null);
list.add(15);
list.add(null);
Integer oldVal = null;
int newVal = 30;
Collections.replaceAll(list, oldVal, newVal);
System.out.println(list); 
Output
[30, 15, 30] 

Reference

Class Collections
POSTED BY
ARVIND RAI
ARVIND RAI










©2022 concretepage.com | Privacy Policy | Contact Us