Java Vector - forEach() Method
The java.util.Vector.forEach() method is used to perform the given action for each element of the iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller.
Syntax
public void forEach(Consumer<? super E> action)
Here, E is the type of element maintained by the container.
Parameters
action |
Specify the action to be performed for each element. |
Return Value
void type.
Exception
Throws NullPointerException, if the specified action is null.
Example:
In the example below, the java.util.Vector.forEach() method is used to print each elements of the given vector.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a vector Vector<Integer> MyVec = new Vector<Integer>(); //populating vector MyVec.add(10); MyVec.add(20); MyVec.add(30); MyVec.add(40); MyVec.add(50); System.out.println("MyVec contains: "); MyVec.forEach((n) -> System.out.println(n)); } }
The output of the above code will be:
MyVec contains: 10 20 30 40 50
Example:
In the example below, the java.util.Vector.forEach() method is used to print string elements of the given vector.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a vector Vector<String> MyVec = new Vector<String>(); //populating vector MyVec.add("UK"); MyVec.add("USA"); MyVec.add("IND"); System.out.println("MyVec contains: "); MyVec.forEach(System.out::println); } }
The output of the above code will be:
MyVec contains: UK USA IND
❮ Java.util - Vector