Java Vector forEach() Method Tutorial

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

What is Java Vector forEach() Method?

The Java Vector forEach() method is used to run a set of instructions for every element of a vector object.

For example, if you have a vector object with 10 digital numbers as its elements and want to multiply each element by 10 and print the result to the console, then you can use this method.

Note: this method cannot be used to change the content of the target vector object.

Java Vector forEach() Method Syntax:

public void forEach(Consumer<? super E> action)

forEach() Method Parameters:

The method has only one parameter and that is of type functional interface consumer.

This means basically we need to pass a reference of a method to this forEach() method.

That reference method is the place where we define the instructions to be executed of each element of a vector object. (Behind the scene, the forEach method calls the reference method and passes each element of the vector object at a time).

Here’s the signature of the reference method:

  • The return value of this method is void.
  • It takes only one argument and that is of the same type as the elements of the target vector object.

You can create this reference method using the lambda expression, or reference an instance or static method.

forEach() Method Return Value:

The return value of the forEach() method is void.

forEach() Method Exceptions:

The method might throw one exception:

NullPointerException: we get this exception if we pass a null value as the argument of this method.

Example: using Vector forEach() 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.forEach(e->{
         System.out.println(e);
      });
    }
}

Output:

1

2

3

4

5
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies