Saturday, 8 June 2019

Java 8 | Internal vs. External Iteration

Iterators are used in Collection framework in Java to retrieve elements one by one.

External iteration

Till Java 7, the collections framework relied on the concept of external iteration, where a Collection provides, by implementing Iterator and clients use this to step sequentially through the elements of a collection. Below given examples to count the even integer in a list.

import java.util.*;
public class CountEven {
       public static void main(String[] args) {
              List<Integer>list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
              int count = 0;
              for (int element : list) {
                      if (element % 2 == 0) {
                             count++;
                      }
              }
              System.out.println("Even number in the list are:" + count);
       }
}

OR we can write like this:

import java.util.*;
public class CountEven {
       public static void main(String[] args) {
              List<Integer>list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
              int count = 0;
              Iterator iterator = list.iterator();
              while (iterator.hasNext()) {
                      int element = iterator.next();
                      if (element%2 == 0) {
                             count++;
                      }
              }
              System.out.println("Even number in the list are:" + count);
       }
}

Above mentioned code snippets are the example of external iteration. External iteration is straightforward enough, but it has several problems:

1) Java’s for-each loop/iterator is inherently sequential, and must process the elements in the order specified by the collection.

2) It limits the opportunity to manage the control flow, which might be able to provide better performance by exploiting reordering of the data, parallelism, short-circuiting, or laziness.


Internal iteration

Sometimes the strong guarantees of the for-each loop (sequential, in-order) are desirable, but often are just disadvantage to performance. The alternative to external iteration is internal iteration, where instead of controlling the iteration, client let it handle by library and only provide the code which must be executed for all/some of data elements.

The internal-iteration equivalent of the previous example is:

import java.util.*;
public class CountEven {
       public static void main(String[] args) {
              List<Integer>list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
              Long count = list.stream().filter(i -> i % 2 == 0).collect(Collectors.counting());
              System.out.println("Even number in the list are:" + count);
       }
}

1 comment:

  1. Thanks for the information...
    Please share your thoughts on stream and parallel stream.. If possible benchmark their performance..
    Thanks 😊

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...