Java Vector replaceAll() Method Tutorial

In this section, we will learn what the Vector replaceAll() method is and how to use it in Java.

What is Java Vector replaceAll() Method?

The Java Vector replaceAll() method is used to replace/ modify the elements of a vector object.

Basically, this method takes a reference to a method as its argument and runs that method for every element of the target vector object.

Inside this reference method is the place where we set a set of instructions that at the end modify the incoming elements of the vector object and produce new replacement values as a result.

Note: this reference method takes the elements of the target vector object as its argument.

Java Vector replaceAll() Method Syntax:

public void replaceAll(UnaryOperator<E> operator)

replaceAll() Method Parameters:

The only parameter of this method is of type UnaryOperator which is a functional interface.

Basically, this method takes a reference to a method. This reference method could be created by the lambda expression, or we could use a reference to an instance or static method if there’s one with the signature that matches the need.

The signature of the reference method should be:

  • It takes one argument of the same type as the elements of the target vector object.
  • The return datatype of this method is also the same as the elements of the target vector object.

replaceAll() Method Return Value:

The return value of this method is void.

replaceAll() Method Exceptions:

The method itself does not throw an exception, but the reference method we pass as its argument might throw one (depending on how the method’s instructions were designed) and its the job of the caller to handle the potential exceptions.

Example: using Vector replaceAll() method

import java.util.Vector; 

public class Main {

    public static void main(String[] args){
        
      Vector <Integer> vector = new Vector<>();
      vector.addElement(1);
      vector.addElement(2);
      vector.addElement(3);
      vector.addElement(4);
      vector.addElement(5);
      
      vector.replaceAll(e-> e*10);
      
      for (int i : vector){
         System.out.println(i);
      }
    }
}

Output:

10

20

30

40

50
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies