Vector的forEach()方法用于对Vector的Iterable的每个元素执行给定操作,直到该方法处理完所有元素或发生异常为止。
如果该方法指定了顺序,则按照迭代顺序执行操作。操作抛出的异常将传递给调用方。
直到并且除非覆盖类指定了并发修改策略,否则操作无法修改元素的基础源,因此可以说此方法的行为未指定。
用法:
public void forEach(Consumer super E> action)
参数:此方法采取参数操作,该参数操作表示要对每个元素执行的操作。
返回值:此方法不返回任何内容。
异常:如果指定的操作为null,则此方法将引发NullPointerException。
以下示例程序旨在说明矢量的forEach()方法:
示例1:在Vector上演示forEach()方法的程序,其中包含String的集合。
// Java Program Demonstrate forEach()
// method of Vector
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create an Vector which going to
// contains a collection of Strings
Vector data = new Vector();
// Add String to Vector
data.add("Saltlake");
data.add("LakeTown");
data.add("Kestopur");
System.out.println("List of Strings data");
// forEach method of Vector and
// print data
data.forEach((n) -> System.out.println(n));
}
}
输出:
List of Strings data
Saltlake
LakeTown
Kestopur
示例2:该程序在包含对象集合的Vector上演示forEach()方法。
// Java Program Demonstrate forEach()
// method of Vector
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create an Vector which going to
// contains a collection of objects
Vector vector = new Vector();
// Add objects to vector
vector.add(new DataClass("Shape", "Square"));
vector.add(new DataClass("Area", "2433Sqft"));
vector.add(new DataClass("Radius", "25m"));
// print result
System.out.println("list of Objects:");
// forEach method of Vector and
// print Objects
vector.forEach((n) -> print(n));
}
// printing object data
public static void print(DataClass n)
{
System.out.println("****************");
System.out.println("Object Details");
System.out.println("key : " + n.key);
System.out.println("value : " + n.value);
}
}
// create a class
class DataClass {
public String key;
public String value;
DataClass(String key, String value)
{
this.key = key;
this.value = value;
}
}
输出:
list of Objects:
****************
Object Details
key : Shape
value : Square
****************
Object Details
key : Area
value : 2433Sqft
****************
Object Details
key : Radius
value : 25m