forEach不修改java(8)集合 [英] forEach not modify java(8) collection

查看:204
本文介绍了forEach不修改java(8)集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个整数列表,我在列表中使用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 a Consumer; i.e. it doesn't generate a value.
  • The semantics don't allow for the this collection to be updated.

这篇关于forEach不修改java(8)集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆