sum of values of two lists in java

18.9k views Asked by At

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

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);


    }

}
3

There are 3 answers

0
Salah On BEST ANSWER

Simply :

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

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.

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, especially not you. Learning computer science is all about experimenting and learning by trial and error.

I suggest you read this page, try to write your own code, 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.

0
shmosel On

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

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