Java Utility Library

Java ArrayList - replaceAll() Method



The java.util.ArrayList.replaceAll() method is used to replace each element of the list with the result of applying the specified unary operator to that element.

Syntax

public void replaceAll(UnaryOperator<E> operator)

Parameters

operator Specify the unary operator to apply to each element.

Return Value

void type.

Exception

NA.

Example:

In the example below, the java.util.ArrayList.replaceAll() method is used to replace each element of the list by using specified unary operator.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating the ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);
    MyList.add(50);

    //printing the ArrayList
    System.out.println("MyList contains: " + MyList);

    //applying ++ operator
    MyList.replaceAll(n -> ++n);

    //printing the ArrayList
    System.out.println("MyList contains: " + MyList);

    //applying += operator
    MyList.replaceAll(n -> n+=5);
 
    //printing the ArrayList
    System.out.println("MyList contains: " + MyList);
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30, 40, 50]
MyList contains: [11, 21, 31, 41, 51]
MyList contains: [16, 26, 36, 46, 56]

❮ Java.util - ArrayList