Java中的 ArrayDeque forEach() 方法
ArrayDeque的forEach()方法继承自接口Java .lang.Iterable 。如果方法指定了该顺序,则该操作按迭代顺序执行。 Method遍历ArrayDeque的Iterable的每个元素,直到所有元素都被该方法处理完或者发生异常。操作抛出的异常被传递给调用者。
句法:
public void forEach(Consumer super E> action)
参数:此方法采用参数名称action ,它表示要对每个元素执行的操作。
返回:此方法不返回任何内容。
异常:如果指定的操作为空,则此方法抛出NullPointerException 。
下面的程序说明了 ArrayDeque 的 forEach() 方法:
示例 1:演示包含字符串值队列的 ArrayDeque 上的 forEach() 方法。
// Java Program Demonstrate forEach()
// method of ArrayDeque
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create an ArrayDeque
// which contains string values
ArrayDeque cities = new ArrayDeque();
// Add Strings to list
cities.add("Kolkata");
cities.add("Delhi");
cities.add("Bombay");
cities.add("Pune");
// forEach method of ArrayDeque and
// print city names
cities.forEach((n) -> System.out.println(n));
}
}
输出:
Kolkata
Delhi
Bombay
Pune
示例 2:演示包含对象队列的 ArrayDeque 上的 forEach() 方法。
// Java Program Demonstrate forEach()
// method of ArrayDeque
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create an ArrayDeque which going to
// contains a list of Objects
ArrayDeque list = new ArrayDeque();
// Add Objects to list
list.add(new batch("CSE", 67));
list.add(new batch("ECE", 57));
list.add(new batch("IT", 90));
list.add(new batch("ME", 78));
// print result
System.out.println("list of Objects:");
// forEach method of ArrayDeque and
// print student names
list.forEach((n) -> print(n));
}
// printing details of object
public static void print(batch n)
{
System.out.println("*******************************");
System.out.println("Batch Name is " + n.name);
System.out.println("No of Students are " + n.noOfStudents);
}
}
// create a class
class batch {
String name;
int noOfStudents;
batch(String name, int noOfStudents)
{
this.name = name;
this.noOfStudents = noOfStudents;
}
}
输出:
list of Objects:
*******************************
Batch Name is CSE
No of Students are 67
*******************************
Batch Name is ECE
No of Students are 57
*******************************
Batch Name is IT
No of Students are 90
*******************************
Batch Name is ME
No of Students are 78
示例 3:演示 ArrayDeque 上 forEach() 方法的 NullPointerException。
// Java Program Demonstrate forEach()
// method of ArrayDeque
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create an ArrayDeque
// which contains string values
ArrayDeque cities = new ArrayDeque();
// Add Strings to list
cities.add("Kolkata");
cities.add("Delhi");
cities.add("Bombay");
cities.add("Pune");
try {
// forEach method of ArrayDeque and
// print city names
cities.forEach(null);
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出:
Exception: java.lang.NullPointerException
参考:
Java Java )