forEach不修改java(8)集合 [英] forEach not modify java(8) collection
问题描述
假设我有一个整数列表,我在列表中使用Java 8 forEach方法将其值加倍。
说我有以下代码:
Say I have an Integer list and I'm using Java 8 forEach method on the list to double its values. Say I have the following code:
List<Integer> l = Arrays.asList(2,3,6,1,9);
l.forEach(p->p*=2);
至于每个方法取消费用并调用它接受方法。
我在运行上面的代码后打印列表,原始列表没有变化。
As forEach method take Consumer and calls it accept methos. I print the list after runnig the above code and the original list doesn't change.
据我所知,Stream不会改变源但是在这里我只是在每个元素上调用accept方法...
As far as I understand Stream doesn't alter the source but here I just call accept method on each element...
在advace中感谢你
Thank u in advace
推荐答案
forEach不改变列表的原因归结为规范:
The reason that forEach does not mutate the list comes down to the specification:
的forEach
说:
默认void forEach(Consumer<?super T> action)
.....默认实现的行为如下:
..... The default implementation behaves as if:
for (T t : this)
action.accept(t);
如您所见:
-
操作
是消费者
;即它不会生成值。 - 语义不允许更新
此
集合。
- The
action
is aConsumer
; i.e. it doesn't generate a value. - The semantics don't allow for the
this
collection to be updated.
这篇关于forEach不修改java(8)集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!