- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to replace an element in a list using Java
Problem Description
How to replace an element in a list
Solution
Following example uses replaceAll() method to replace all the occurance of an element with a different element in a list.
import java.util.*; public class Main { public static void main(String[] args) { List list = Arrays.asList("one Two three Four five six one three Four".split(" ")); System.out.println("List :"+list); Collections.replaceAll(list, "one", "hundread"); System.out.println("replaceAll: " + list); } }
Result
The above code sample will produce the following result.
List :[one, Two, three, Four, five, six, one, three, Four] replaceAll: [hundread, Two, three, Four, five, six, hundread, three, Four]
java_collections.htm
Advertisements