Collection.forEach() 和 Collection.stream().forEach() 用于迭代集合,两者之间没有太大区别,因为它们都给出了相同的结果,尽管它们的内部有一些差异在职的。
Collection.stream().forEach()基本上用于通过将集合转换为流然后迭代集合流来迭代一组对象。在迭代集合时,如果对集合进行任何结构更改,则会抛出并发修改异常。
Collection.forEach()使用集合的迭代器(以指定者为准)。大多数集合在迭代该集合时不允许修改结构。如果该集合发生任何更改,即添加元素或删除元素,则它们将引发并发修改错误。如果 collection.forEach() 正在迭代同步集合,那么它们将锁定集合段并将其保留在可以对该集合进行的所有调用上。
Collection.stream().forEach() 和 Collection.forEach() 的区别
Collection.stream().forEach() |
Collection.forEach() |
---|---|
Collection.stream().forEach() is also used for iterating the collection but it first converts the collection to the stream and then iterates over the stream of collection. | Collection.forEach() uses the collections iterator. |
Unlike Collection.forEach() it does not execute in any specific order, i.e. the order is not defined. | If always execute in the iteration order of iterable, if one is specified. |
During structure modification in the collection, the exception will be thrown later. | If we perform any structural modification in the collection by using the collection.forEach() it will immediately throw an exception. |
If iteration is happening over the synchronized collection, then it does not lock the collection. | If iteration is happening over the synchronized collection, then it locks the collection and holds it across all the calls. |
下面是一个Java程序,用于展示 Collection.stream.forEach() 的用法:
Java
// Java Program to show the demonstration of
// Collection.stream().forEach()
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
List list = new ArrayList<>();
list.add(5);
list.add(6);
list.add(3);
list.add(4);
// printing each element of list using forEach loop
list.stream().forEach(System.out::print);
}
}
Java
// Java Program to show the demonstration of
// Collection.forEach()
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
List list = new ArrayList<>();
list.add(5);
list.add(6);
list.add(3);
list.add(4);
// printing each element of list
list.forEach(System.out::print);
}
}
输出
5634
下面是一个Java程序来展示 Collection.forEach() 方法的用法:
Java
// Java Program to show the demonstration of
// Collection.forEach()
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
List list = new ArrayList<>();
list.add(5);
list.add(6);
list.add(3);
list.add(4);
// printing each element of list
list.forEach(System.out::print);
}
}
输出
5634