
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 in 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]
Advertisements