- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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]
- Related Articles
- Replace All Elements Of ArrayList with with Java Collections
- Find maximum element of ArrayList with Java Collections
- Find minimum element of ArrayList with Java Collections
- Reverse order of all elements of ArrayList with Java Collections
- Shuffle elements of ArrayList with Java Collections
- Swap elements of ArrayList with Java collections
- Java Program to replace all occurrences of given String with new one
- Copy Elements of One ArrayList to Another ArrayList with Java Collections Class
- Java Program to replace all occurrences of a given character with new character
- Add an element to specified index of ArrayList in Java
- Get Enumeration over ArrayList with Java Collections
- How to replace an element of an ArrayList in Java?
- Replace All Occurrences of a Python Substring with a New String?
- Perform Binary Search on ArrayList with Java Collections
- Insert all elements of other Collection to Specified Index of Java ArrayList

Advertisements