This is more of a coding stretch than a challenge.
Write functions that compute the sum of the numbers in a given list using a for-loop, for each loop, new Java 8 streams, a while-loop, and recursion.
public class Main {
public static void main(String[] args) throws Exception {
List<Integer> numbers = new ArrayList<>(
Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9));
int sumJavaStream = sumJavaStream(numbers);
int sumForLoop = sumForLoop(numbers);
int sumForEachLoop = sumForEachLoop(numbers);
int sumDoWhile = sumWhile(numbers);
int sumRecursion = sumRecursion(numbers);
if (sumDoWhile == sumForLoop && sumForLoop == sumForEachLoop &&
sumForEachLoop == sumDoWhile && sumDoWhile == sumRecursion) {
System.out.println(sumJavaStream);
}
}
private static int sumJavaStream(List<Integer> numbers) {
return numbers.stream().mapToInt(num -> num.intValue()).sum();
}
private static int sumForLoop(List<Integer> numbers) {
int result = 0;
for (int i = 0; i < numbers.size(); i++) {
result += numbers.get(i).intValue();
}
return result;
}
private static int sumForEachLoop(List<Integer> numbers) {
int result = 0;
for (Integer number : numbers) {
result += number.intValue();
}
return result;
}
private static int sumWhile(List<Integer> numbers) {
int result = 0;
int i = 0;
while (i < numbers.size()) {
result += numbers.get(i).intValue();
i++;
}
return result;
}
private static int sumRecursion(List<Integer>> numbers) {
return sumRecursion(numbers, 0, 0);
}
private static int sumRecursion(List<Integer> numbers, int index, int sum) {
int result = sum;
if (index < numbers.size()) {
result += numbers.get(index);
result = sumRecursion(numbers, index + 1, result);
}
return result;
}
}
Related Content