Monday 17 August 2015

For loop in Java

In java 8 there is a new way to use for loop. There is a new foreach() method in java.util.stream.Stream class.

Pre JDK 5
      for(int i=0; i < countries.size(); i++)
      {
          System.out.println(countries.get(i));
      }

In JDK5
    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.

JDK8
       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));