The syntax of the replaceAll()
method is:
arraylist.replaceAll(UnaryOperator<E> operator)
Here, arraylist is an object of the ArrayList class.
replaceAll() Parameters
The replaceAll()
method takes a single parameter.
- operator - operation to be applied to each element
replaceAll() Return Value
The replaceAll()
method does not return any values. Rather, it replaces all value of the arraylist with new values from operator.
Example 1: Change All Elements to Uppercase
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// create an ArrayList
ArrayList<String> languages = new ArrayList<>();
// add elements to the ArrayList
languages.add("java");
languages.add("javascript");
languages.add("swift");
languages.add("python");
System.out.println("ArrayList: " + languages);
// replace all elements to uppercase
languages.replaceAll(e -> e.toUpperCase());
System.out.println("Updated ArrayList: " + languages);
}
}
Output
ArrayList: [java, javascript, swift, python] Updated ArrayList: [JAVA, JAVASCRIPT, SWIFT, PYTHON]
In the above example, we have created an arraylist named languages. Notice the line,
languages.replaceAll(e -> e.toUpperCase());
Here,
e -> e.toUpperCase()
is a lambda expression. It converts all elements of the arraylist into uppercase. To learn more, visit Java Lambda Expression.replaceAll()
- Replaces all elements of the arraylist into uppercase.
Example 2: Multiply All Elements of ArrayList by 2
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// create an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
// add elements to the ArrayList
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("ArrayList: " + numbers);
// multiply 2 to all elements of the hashmap
numbers.replaceAll(e -> e * 2);;
System.out.println("Updated ArrayList: " + numbers);
}
}
Output
ArrayList: [1, 2, 3] Updated ArrayList: [2, 4, 6]
In the above example, we have created an arraylist named numbers. Notice the line,
numbers.replaceAll(e -> e * 2);
Here,
e -> e * 2
- multiply each element of the arraylist by 2replaceAll()
- replaces all elements of the arraylist with results ofe -> e * 2
Note: We can also use the Collections.replace() method to perform the exact operation in Java.
Also Read: