Java ArrayList replaceAll() Method
The replaceAll() method is used to replace each element in the array with the given operation.
The syntax of the replaceAll() method is:
arraylist.replaceAll(UnaryOperator<E> operator)
Note:arraylist is an object of the ArrayList class.
Parameter Description:
- operator - the element or series of operations to be applied to the dynamic array
Return Value
No return value.
Example
The following example demonstrates the use of the replaceAll() method:
Example
import java.util.*;
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
sites.add("Google");
sites.add("Example");
sites.add("Taobao");
System.out.println("ArrayList : " + sites);
// Change all elements to uppercase
sites.replaceAll(e -> e.toUpperCase());
System.out.println("Updated ArrayList: " + sites);
}
}
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
sites.add("Google");
sites.add("Example");
sites.add("Taobao");
System.out.println("ArrayList : " + sites);
// Change all elements to uppercase
sites.replaceAll(e -> e.toUpperCase());
System.out.println("Updated ArrayList: " + sites);
}
}
Executing the above program outputs the result:
ArrayList : [Google, Example, Taobao] 更新后的 ArrayList: [GOOGLE, EXAMPLE, TAOBAO]
Multiply all elements in the dynamic array by 2:
Example
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Create a dynamic array
ArrayList<Integer> numbers = new ArrayList<>();
// Add elements to the array
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("ArrayList: " + numbers);
// Multiply all elements by 2
numbers.replaceAll(e -> e * 2);;
System.out.println("Updated ArrayList: " + numbers);
}
}
class Main {
public static void main(String[] args) {
// Create a dynamic array
ArrayList<Integer> numbers = new ArrayList<>();
// Add elements to the array
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("ArrayList: " + numbers);
// Multiply all elements by 2
numbers.replaceAll(e -> e * 2);;
System.out.println("Updated ArrayList: " + numbers);
}
}
Executing the above program outputs the result:
ArrayList: [1, 2, 3] 更新后的 ArrayList: [2, 4, 6]
In the above example, we created an array named numbers.
Note this line:
numbers.replaceAll(e -> e * 2);
- e -> e * 2- multiplies each element in the dynamic array by 2
- replaceAll()- replaces the elements in the array with the result of e -> e * 2.
Java ArrayList