Thursday, August 20, 2015

Loop iteration redefined with java 8 Stream


for loop is there in many programming languages like C, C++ java C# etc and it is used mainly iterating contents of same type.

for loop has come a long way in Java 8 with new forEach() method in java.util.stream.Stream class.

We will check in the following post how every release of java has given us more and more compact and enhanced looping experience by time.

Pre JDK 1.5, this was the way of iterating over an Collection let’s say ArrayList:
// Before JDK 1.5, printing each element of List using for
List  countries = Arrays.asList("India", "Australia", "England", "South Africa");

for(int i=0; i < countries.size(); i++)
{
  System.out.println(countries.get(i));
}
So when foreach loop or advanced for loop was added on Java 5, we started to following style of looping over Collection or List :
for(String country : countries){
      System.out.println(country);
}
This was much shorter, cleaner and less error prone than previous one and everybody loved it. You don't need to keep track of index, you don't need to call size() method in every step and it was less error prone than previous one, but it was still imperative. You are telling compiler what to do and how to do like traditional for loop.

Now comes the era of Lambda Expressions where things changes drastically when functional style of programming was introduced in Java 8 via lambda expression and new Stream API. Now you can loop over your collection without any loop in Java, you just need to use forEach() method of java.util.Stream class, as shown below :

countries.stream().forEach(str -> System.out.println(str));


This code has reduced looping over collection or list into just one line.
To add into, If you want to perform some pre processing task e.g. filtering, conversion or mapping, you can also do this in same line, as shown below:

countries.stream().filter(country ->
country.contains("n")).forEach(str -> System.out.println(str));

3 comments:

  1. If we are not calling the size then how many times loop will perform.?

    ReplyDelete
  2. @Adarsh: Then it will give you a compile time error. Since the comparison should be done on same data types so if you are not calling size() on countries this will result an integer to Collection type comparison which is syntactically wrong.

    ReplyDelete

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...