Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java / Java8

Fun with Loops - 7 Ways To Do Loops in Java 8

0.00/5 (No votes)
30 Jun 2015CPOL 5.7K  
An coding exercise using Java 8 trying to do the same summation loop multiple ways

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.
Java
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)