Easy Tutorial
❮ Data Queue String Format ❯

Java ArrayList replaceAll() Method

Java ArrayList

The replaceAll() method is used to replace each element in the array with the given operation.

The syntax for the replaceAll() method is:

arraylist.replaceAll(UnaryOperator<E> operator)

Note: arraylist is an object of the ArrayList class.

Parameter Description:

Return Value

This method does not return any 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 an ArrayList
        ArrayList<String> sites = new ArrayList<>();

        sites.add("Google");
        sites.add("tutorialpro");
        sites.add("Taobao");

        System.out.println("ArrayList : " + sites);

        // Change all elements to uppercase
        sites.replaceAll(e -> e.toUpperCase());
        System.out.println("Updated ArrayList: " + sites);
    }
}

Output of the above program is:

ArrayList : [Google, tutorialpro, Taobao]
Updated ArrayList: [GOOGLE, TUTORIALPRO, TAOBAO]

Multiply all elements in the dynamic array by 2:

Example

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // Create an ArrayList
        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);
    }
}

Output of the above program is:

ArrayList: [1, 2, 3]
Updated ArrayList: [2, 4, 6]

In the above example, we created an array named numbers.

Notice this line:

numbers.replaceAll(e -> e * 2);

Java ArrayList

❮ Data Queue String Format ❯