Overview of Java 8 Streams

Posted By Gursahib Singh | 30-Jul-2018

To iterate a certain amount of code we require loops in our programming which has some shortcomings like bulkier or complex code,no parallel execution etc.

Suppose we want to find the sum of integers greater than 10 over a list of integers.Before java 8 the approach for the same would be:

    private static int sumIterator(List list) {
		Iterator it = list.iterator();
		int sum = 0;
		while (it.hasNext()) {
			int num = it.next();
			if (num > 10) {
				sum += num;
		return sum;

To overcome these shortcommings java 8 stream apis are introduced which provide internal looping or internal iteration.
The key features of Stream apis include :
1. It works on sequential approach i.e it provides the internal iteration which acts on the Collection objects sequentially there by eleminating the use or necessity of external loops.

2. Parallel stream apis provide the internal iteration which provides the parallel execution of the Collection objects.

3. The method argument of most of java 8 stream apis are functional interfaces which allows the use of lambda expressions with them.

Now by using the java 8 stream apis and lambda expressions the above code can be written as follows:

    private static int sumStream(List list) {
		return list.stream().filter(i -> i > 10).mapToInt(i -> i).sum();

This code uses the basic iteration,filtering and mapping strategy to increase the efficiency and performance.

Parallel approach is used when the sequence to operate on each object of the collection is not a requirement. The code to chieve the above result using parallel approach is:

    private static int sumStream(List list) {
		return list.parallelStream().filter(i -> i > 10).mapToInt(i -> i).sum();

However in the parallel stream,the  common fork-join thread pool is used which means if a long running task is submitted, all threads in the pool may get blocked and eventually all the tasks which are using parallel streams may also get blocked eventually resulting in low performance and efficiency.
This is the basic overview of the Stream and parallel Stream Apis of java 8.

Request for Proposal

Recaptcha is required.

Sending message..