-4
public static ArrayList<Integer> q3(ArrayList<Integer> listOfIntegers){
    ArrayList<Integer> listOfIntegers1 = new ArrayList<Integer>();
    listOfIntegers1.add(16);
    listOfIntegers1.add(6);
    listOfIntegers1.add(10);
    listOfIntegers1.add(12);
    return listOfIntegers1;
}

I have to take an ArrayList of Integers as a parameter and return an int. The returned int should be the sum of the values int the input ArrayList at indices 16, 6, 10, and 12. How would i go about doing this?

Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
J.Doe
  • 15
  • 1
  • 6
  • 2
    You iterate the list and add up the values. – daniu Feb 08 '18 at 15:07
  • Just add the values at those found indices and return the result. What's stopping you? – tobias_k Feb 08 '18 at 15:08
  • 1
    Why are you _adding_ those values to the list? And why are you creating a new list at all, if you just want to return a single number? Do you know what `add` does? – tobias_k Feb 08 '18 at 15:11
  • @tobias_k as I understand he wants to add the values at the indexes given in the second list (`listOfIntegers1`) above... (Hint to OP): something like `listOfIntegers.get(listOfIntegers1.get(0)) + listOfIntegers.get(listOfIntegers1.get(1)) + ...` – user85421 Feb 08 '18 at 15:45
  • and another hint to the author: use some meaningful names for variables, parameters and method... helps a lot ALWAYS – user85421 Feb 08 '18 at 15:46
  • Yea sorry guys i realized i could have made this clearer, im very new to java and coding in general, i apologize and will try to make the question clearer next time, thank you all for your help. – J.Doe Feb 09 '18 at 16:05

1 Answers1

1

Just use IntStream::sum after filtering the values using the list of indexes:

List<Integer> listOfIntegers = Arrays.asList(0,1,2,3,4,5,100,7,8,9,100,11,100,13,14,15,100,17);
List<Integer> listOfIndexes = Arrays.asList(16,6,10,12);

return listOfIntegers
        .stream()
        .filter(i -> listOfIndexes.contains(listOfIntegers.indexOf(i))
        .mapToInt(Integer::intValue)
        .sum();

Output:

400

Or even better to avoid iterating the whole listOfIntegers:

return listOfIndexes
         .stream()
         .mapToInt(idx -> listOfIntegers.get(idx))
         .sum();

But this way could cause an ArrayIndexOutOfBoundsException if a given index is out of the range of the listOfIntegers.

Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50