Java中的Vector forEach()方法

这个 forEach() 向量的方法用于对向量的Iterable的每个元素执行给定的操作,直到该方法处理完所有元素或发生异常为止。

null

如果方法指定了顺序,则按迭代顺序执行操作。操作引发的异常会传递给调用方。

除非重写类指定了并发修改策略,否则操作无法修改元素的底层源,因此我们可以说此方法的行为未指定。

在Java中从集合中检索元素 .

语法:

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

参数: 此方法接受一个参数 行动 表示每个元素要执行的操作。

返回值: 此方法不返回任何内容。

例外情况: 这个方法抛出 空指针异常 如果指定的操作为空。

下面的程序演示了向量的forEach()方法:

例1: 该程序用于在包含字符串集合的向量上演示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: 该程序用于在包含对象集合的向量上演示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)

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享