• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java 8 streams  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Before we start to understand how streams work in Java 8, lets first try to find out what is the use of Java streams.

Consider the below example- In this you have to iterate over an array and then calculate the sum of all numbers which are greater than 10.

Java code- without using Streams would be like

public int getSum(List<Integer> list)
{
int sum=0;
for(Integer num : list){

if(num>10)
sum+=num;

}
return num;
}

If we use streams to do the implement the above logic , the code will look like
private static int sumStream(List<Integer> list) {
return list.stream().filter(i -> i > 10).mapToInt(i -> i).sum();
}

This would also increase efficiency as the iteration over the array will be performed by the Java itself, and we don't have to give an external iteration.


Relationship between Java Collections and Streams
A collection is an in-memory data structure which is used to hold the values during program execution whereas a stream does not hold data. It process on the source data collection on-demand whenever some processing has to happen. For example, in the above example , the underlying data structure in the ArrayList and while iterating the streams comes into picture, only for the processing part.

Java 8 Stream support sequential as well as parallel processing, parallel processing can be very helpful in achieving high performance for large collections.
 
Marshal
Posts: 56871
174
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I shall duplicate this discussion in our Java8 forum.

You wrote wrote:

I would indent that code differently, and I wouldn't make it a method on its own. Consider the Stream invocation to be an expression rather than a block:-I am pretty sure there are other ways you can write that: for example, you can probably use the method reference Integer::intValue instead of the λ in line 3.You can probably get a sum with the collect() method or reduce(), but the sum() method on an IntStream may give faster execution.
There are lots of other reasons for using Streams, including ease of parallelisation and more concise code which is easier to read.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!