java java中两个列表的值之和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30725466/
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-11-02 17:33:56  来源:igfitidea点击:

sum of values of two lists in java

javaarraylistsum

提问by suleman bader

I am working on a java project and I am having a problem. I want to have the sum of two lists aand bin list cbut I don't know how to do that. I want a.add(3) +b.add(4)should be in next list cwhere the value should be 7 similarly for 5+2=6 1+(-4)=-3 any suggestion and help would be appreciated

我正在处理一个 Java 项目,但遇到了问题。我想要两个列表ab列表的总和,c但我不知道该怎么做。我希望a.add(3) +b.add(4)应该在下一个列表c中,对于 5+2=6 1+(-4)=-3,任何建议和帮助的值都应该为 7,我们将不胜感激

Code:

代码:

import java.util.ArrayList;  
import java.util.List; 

public class Test {

    public static void main(String[] args) {
        List<Integer> a = new ArrayList<Integer>();
        List<Integer> b = new ArrayList<Integer>();
        List<Integer> three= new ArrayList<Integer>();

        a.add(3);
        a.add(5);
        a.add(1);
        a.add(-2);

        b.add(1);
        b.add(2);
        b.add(-4);
        b.add(3);


    }

}

回答by shmosel

No elementary question is truly complete without an answer that uses Streams. Here you go:

没有使用 Streams 的答案,任何基本问题都不是真正完整的。干得好:

List<Integer> result = IntStream.range(0, a.size())
         .mapToObj(i -> a.get(i) + b.get(i))
         .collect(Collectors.toList());

回答by Salah

Simply :

简单地 :

for (int i = 0; i < a.size(); i++) {
        result.add(a.get(i) + b.get(i));
}

回答by johnny_boy

While using

使用时

for (int i = 0; i < a.size(); i++)
{
    result.add(a.get(i) + b.get(i));
}

As per Salah's answer is correct, I don't think it's the best option for you.

根据 Salah 的回答是正确的,我认为这不是您的最佳选择。

Not knowing how to add up 2 arrays shows a fundamental lack of understanding. Just asking for code to paste on the end of your function won't help anyone, especiallynot you. Learning computer science is all about experimentingand learning by trial and error.

不知道如何将 2 个数组相加表明基本缺乏理解。仅仅要求将代码粘贴到您的函数末尾对任何人都没有帮助,尤其是对您而言。学习计算机科学就是通过反复试验进行实验和学习。

I suggest you read this page, try to write your owncode, and come back here with questions if your code doesn't work. You will learn a lot more that way.

我建议您阅读此页面,尝试编写自己的代码,如果您的代码不起作用,请回到这里提出问题。这样你会学到更多。

If you have read the page and still don't understand, don't feel bad. Comment on my answer and I will write a short explanation of how Java for loops and arrays work.

如果您已阅读该页面但仍然不明白,请不要难过。评论我的回答,我将简要说明 Java for 循环和数组的工作原理。