英文:
Increase all items in an ArrayList<Integer> by a given amount with a lambda function
问题
在我的 Pixel 类中,我有以下的代码:
class Pixel {
    ArrayList<Integer> values = new ArrayList<Integer>();
    ...
    public void brighten(int amount) {
        this.values.forEach((Integer value) -> {
            value += amount;
        });
    }
    ...
}
我可以避免创建 newValues,并且在 lambda 函数中直接增加 values ArrayList 中的值吗?
英文:
In my Pixel class I have the following code
class Pixel {
    ArrayList<Integer> values = new ArrayList<Integer>();
    ...
    public void brighten(int amount) {
        ArrayList<Integer> newValues = new ArrayList<>();
        this.values.forEach((Integer value) -> newValues.add(value + amount));
        this.values = newValues;
    }
    ...
}
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来完成这个任务:
values.replaceAll(i -> i + amount);
英文:
I would use replaceAll for that job:
values.replaceAll(i -> i + amount);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论