使用 lambda 函数将 ArrayList<Integer> 中的所有项增加指定的数量。

huangapple go评论89阅读模式
英文:

Increase all items in an ArrayList<Integer> by a given amount with a lambda function

问题

在我的 Pixel 类中,我有以下的代码:

  1. class Pixel {
  2. ArrayList<Integer> values = new ArrayList<Integer>();
  3. ...
  4. public void brighten(int amount) {
  5. this.values.forEach((Integer value) -> {
  6. value += amount;
  7. });
  8. }
  9. ...
  10. }

我可以避免创建 newValues,并且在 lambda 函数中直接增加 values ArrayList 中的值吗?

英文:

In my Pixel class I have the following code

  1. class Pixel {
  2. ArrayList&lt;Integer&gt; values = new ArrayList&lt;Integer&gt;();
  3. ...
  4. public void brighten(int amount) {
  5. ArrayList&lt;Integer&gt; newValues = new ArrayList&lt;&gt;();
  6. this.values.forEach((Integer value) -&gt; newValues.add(value + amount));
  7. this.values = newValues;
  8. }
  9. ...
  10. }

Is there a way I can avoid creating newValues and increase the values in the values ArrayList directly in the lambda function?

答案1

得分: 8

我会使用replaceAll来完成这个任务:

  1. values.replaceAll(i -> i + amount);
英文:

I would use replaceAll for that job:

  1. values.replaceAll(i -&gt; i + amount);

huangapple
  • 本文由 发表于 2020年7月26日 07:57:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63094761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定