-4

I am trying to subtract two array lists. Both arraylists contain the following data

[1, 1, 5, 1, 1]

I am using an Apache library to perform the operation.

List resultList = ListUtils.subtract(sections, sections);

The operation completes but my result is the following

[]

When I need to it be

[0, 0, 0, 0, 0]

How would I go about doing this?

  • 2
    You should start by looking at the documentation of `ListUtils.subtract` hint: it doesn't do what you think. http://idownvotedbecau.se/noresearch/ – Oleg Oct 17 '17 at 23:41
  • `section.replaceAll(e -> 0);` – shmosel Oct 17 '17 at 23:42
  • 1
    Possible duplicate of [How to subtract values of two lists/arrays in Java?](https://stackoverflow.com/questions/40644999/how-to-subtract-values-of-two-lists-arrays-in-java) – azurefrog Oct 17 '17 at 23:42

1 Answers1

0

Why not do it explicitly with a for loop?

 // Initialize both lists
 List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(1, 1, 5, 1, 1));
 List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(1, 1, 5, 1, 1));

for(int i=0; i < list1.size(); ++i){
     // This is doing the subtraction and assigning the values to
     // list1. If you need a new list, declare it and proceed similarly
     list1.set(i, list1.get(i) - list2.get(i));
}
System.out.println(list1); // output: [0, 0, 0, 0, 0]

You can look at some more information on the set function here: https://www.tutorialspoint.com/java/util/arraylist_set.htm

alejandrogiron
  • 544
  • 2
  • 7
  • 18