forEach 不修改 java(8) 集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23852286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:34:03  来源:igfitidea点击:

forEach not modify java(8) collection

javajava-8

提问by user1409534

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:

假设我有一个整数列表,我在列表上使用 Java 8 forEach 方法将其值加倍。假设我有以下代码:

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.

至于 forEach 方法采用 Consumer 并调用它接受方法。我在运行上面的代码后打印列表,原始列表没有改变。

As far as I understand Stream doesn't alter the source but here I just call accept method on each element...

据我了解 Stream 不会改变源,但在这里我只是在每个元素上调用 accept 方法......

Thank u in advace

提前谢谢你

采纳答案by Stephen C

The reason that forEach does not mutate the list comes down to the specification:

forEach 不改变列表的原因归结为规范:

The javadoc for forEachsays:

javadoc forforEach说:

default void forEach(Consumer<? super T> action)

..... The default implementation behaves as if:

     for (T t : this)
         action.accept(t);

default void forEach(Consumer<? super T> action)

..... 默认实现的行为就像:

     for (T t : this)
         action.accept(t);

As you can see:

如你看到的:

  • The actionis a Consumer; i.e. it doesn't generate a value.
  • The semantics don't allow for the thiscollection to be updated.
  • action是一个Consumer; 即它不产生值。
  • 语义不允许this更新集合。

回答by Masudul

Try to use mapinsted of forEachto alter original List.

尝试使用mapinsted offorEach更改原始List.

List<Integer> list = Arrays.asList(2,3,6,1,9);
list=list.stream().map(p -> p * 2).collect(Collectors.toList());
System.out.println(list);

回答by nosid

The method forEachonly iterates through the elements of the list without changing them, If you want to change the elements, you can use the method replaceAll:

该方法forEach仅遍历列表中的元素而不更改它们,如果要更改元素,可以使用该方法replaceAll

List<Integer> l = Arrays.asList(2,3,6,1,9);
l.replaceAll(p->p*2);