Internal Iteration vs. External Iteration
External Iteration
When operating with Java Collections we use external iteration.
In external iteration we use a for or for each loop or obtain an iterator for a collection and process elements of the collections in a sequence.
The following code computes the sum of squares of all odd integers in the list.
It uses for each loop to access every single element in the list then uses if statement to filter odd integers.
After that it calculates the square and finally stores the sum of square with sum
variable.
import java.util.Arrays;
import java.util.List;
/* ww w .j a v a2 s .c o m*/
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = 0;
for (int n : numbers) {
if (n % 2 == 1) {
int square = n * n;
sum = sum + square;
}
}
System.out.println(sum);
}
}
The code above generates the following result.
Internal Iteration
We can rewrite the code above using stream. It does exactly the same.
import java.util.Arrays;
import java.util.List;
//from www . j ava 2 s . com
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.filter(n -> n % 2 == 1)
.map(n -> n * n)
.reduce(0, Integer::sum);
System.out.println(sum);
}
}
In the code above we didn't use loop statement to iterate through the List. We did the loop internally by stream.
For the odd integer calculation we used lambda expression. We first did the filter then map then reduce.
The code above generates the following result.