Java中的Vector forEach()方法
Vector的 forEach() 方法用于对Vector的每个元素执行给定操作,直到方法处理所有元素或发生异常。
如果该方法指定了顺序,则操作按照迭代顺序执行。操作抛出的异常会传递给调用者。
除非覆盖类已指定了并发修改策略,否则该操作无法修改元素的基础来源,因此我们可以说该方法的行为未指定。
从Java集合中检索元素。
语法:
public void forEach(Consumer<? super E> action)
参数: 该方法需要一个参数操作,该操作代表要对每个元素执行的操作。
返回值: 该方法不返回任何东西。
异常: 如果指定的操作为null,则该方法会抛出NullPointerException异常。
下面的程序说明了Vector的forEach()方法:
示例1: 演示在包含String集合的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 Strings
Vector<String> data = new Vector<String>();
// 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<DataClass> vector = new Vector<DataClass>();
// 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
参考资料: https://docs.oracle.com/javase/10/docs/api/java/util/Vector.html#forEach(java.util.function.Consumer)
极客教程