Java 8 – First Step Towards Functional & Declarative Programming
Object Oriented Programming, the leading style of programming, has became very popular in the last few decades. Though OO existed even before the advent of C++, true potential of OO unleashed with the launching of C++
C++ is a mixture of structured and OO style. Bjarne Stroustroup invented C++ as part of a project he was working on. This project of his required better performance than what was offered by the conventional languages back then. He wasn’t trying to make something perfect, which is probably the reason behind the highly unpredictable behavior of C++, which it inherited from its parent “C”
JAVA entered flashily with their light weight client side programs called Applets. It was not very late, when people realized that there is more to this new coffee bean than just being a client side entity.
Apart from being a good OO solution, Java addressed the biggest challenge in C++, providing Garbage collection for automatically cleaning up the memory & portability regardless of platform. These two features triggered the evolution of a new era in which JAVA flourished as a platform as well as a language.
Pointers in C/C++ was considered complex and evil, so Java removed pointers. But, ask yourself, can a language work without pointers? It is not possible right. Java diplomatically renamed them as “References” and removed arithmetic operations on them. Smart, right? They didn’t expose unnecessary interfaces, and made the run time to carry out difficult things for you. I mean this is what abstraction and encapsulation is all about, which is blabbered all the time while talking about Java.
So, it turned out that everything became OO. People started thinking, talking & eating in terms of Objects. With Java, it became a monotonic idiom to define a class for doing anything. But, Why do we need to create a class every time I need to add something. Why do we always have to talk in terms of classes, when just a function/method would suffice. An example of such case would be a class with only static methods like java.lang.Math
The Imperative style of programming in Java started frustrating developers
JAVA Imperative Style Code (Java 7)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ImperativeStyleDemo {
public static void main(String []args){
List numbers = Arrays.asList(1, 2, 3, 4, 5);
List modifiedNumbers = new ArrayList<>();
for(Integer number: numbers){
if(isEven(number))
modifiedNumbers.add(ImperativeStyleDemo.doubleInteger(number));
}
for(String number: modifiedNumbers){
System.out.println(number);
}
}
public static String doubleInteger(Integer number){
return String.valueOf(number*2);
}
public static Boolean isEven(Integer number){
return number%2==0;
}
}
I mean look at this code, just to display double of even numbers in a list, I had to explicitly tell the compiler to loop through and do all the ceremony for me. It might not look complex to a Java programmer, but it is fairly complex for a newbie.
Then, writing a thread safe code isn’t very easy. I never get it right, I mean, synchronized keyword has a lot of evil around it.
Isn’t it going the same way it went with the pointers in C++? Such complex details should be handled by the run time itself, without letting the programmer know about the complexities buried deep within.
So what’s next?
The idea lead to use the functional style of programming along with Object style, a hybrid language with declarative style of programming instead of imperative style.
But, there is more to JVM than what Java exposes and people always want to keep using that. Why would we want to lose the advantages of JVM just because the interface (Java Language) is not fulfilling our desires. So why not build a declarative functional style language using Java itself which use JVM as a platform. Cool right? This idea gave birth to many JVM languages including Groovy, Scala, Clojure, JRuby, etc
Now let’s look at some code in Groovy to do the same stuff
Groovy Declarative Style Code
[1,2,3,4,5].findAll { it % 2 == 0 }.each() {value->println "${value*2}"};
This is a declarative way of programming and there are many such examples available on internet.
Now the threat that JAVA will decay as a language has reached Oracle/Sun as well. So there has been a lot of work going on to address this stuff in Java 8. So let’s have a look to do the same stuff in Java 8
JAVA Declarative Style Code (Java 8 – Lambda Project)
import java.util.Arrays;
import java.util.List;
class DeclarativeStyle {
public static void main(String []args){
List numbers = Arrays.asList(1,2,3,4, 5, 6);
numbers.stream() //A Fancy Collection
.filter(DeclarativeStyle::isEven) //Filter the data
.map(DeclarativeStyle::doubleInteger) //Map new values
.forEach(System.out::println); //Iterate & perform the operation
}
public static String doubleInteger(Integer number){
return String.valueOf(number * 2);
}
public static Boolean isEven(Integer number){
return number%2==0;
}
}
The first three method calls are just lazy calls, so the list doesn’t iterates till “forEach” is called. Plus, If you do a find operation on a list, then the iteration stops then and there if the element is found. So in a way, we can say that the iterations in Java 8 has been optimized a lot, though the same can be achieved using the existing implementations in Google Guava APIs
The most important thing to notice here is Immutability. The existing collection “numbers” isn’t tampered with in any of the operation. So every method call is pure and hence can be performed interchangeably using multithreading. Let’s have a look at this.
Using Stream (Sequential Flow)
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class SequentialStreamDemo {
public static void main(String []args){
long start = System.currentTimeMillis();
List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
List modifiedNumbers = numbers.stream()
.filter(SequentialStreamDemo::isEven)
.map(SequentialStreamDemo::doubleInteger)
.collect(toList());
modifiedNumbers.forEach(System.out::println);
long end = System.currentTimeMillis();
System.out.println("Time taken =>"+(end-start)/1000f+" seconds");
}
public static String doubleInteger(Integer number){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return String.valueOf(number * 2);
}
public static Boolean isEven(Integer number){
return number%2==0;
}
}
This program takes around 4.063 seconds in my machine. There are four Even Numbers, so there is a delay of 4 seconds added deliberately by Thread.sleep()
Now let’s have a look at the parallel stream. Just change the class name to ParallelStreamDemo & method call to
Using Stream (Parallel Flow)
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class ParallelStreamDemo {
public static void main(String []args){
long start = System.currentTimeMillis();
List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
List modifiedNumbers = numbers.parallelStream()
.filter(ParallelStreamDemo::isEven)
.map(ParallelStreamDemo::doubleInteger)
.collect(toList());
modifiedNumbers.forEach(System.out::println);
long end = System.currentTimeMillis();
System.out.println("Time taken =>"+(end-start)/1000f+" seconds");
}
public static String doubleInteger(Integer number){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return String.valueOf(number * 2);
}
public static Boolean isEven(Integer number){
return number%2==0;
}
}
Now we are using the parallel streaming which interns use a separate thread for every stream. Guess what, the time taken now turns out to be 1.067 seconds
We could’ve achieved the same in previous versions of Java as well, but it will require relatively high LOC.
Awesome, right. Finally Java people has started removing the ceremonial activities involved. Java 8 is not yet released, but we have early release versions in the market. So you can go and play around.
There is a lot more to Java 8 than what I mentioned, which includes, easy operations on the collections, using multi cores & threads without writing any complex synchronized code.
Hope it is not too late for Java to introduce this stuff in Java language.
Looking forward to more cool stuff

Sounds interesting !!
And nice explaination , but we have to see how the developers could mould themselves in the colors of Java8.