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 Listcountries = Arrays.asList("India", "Australia", "England", "South Africa"); for(int i=0; i < countries.size(); i++) { System.out.println(countries.get(i)); }
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));