Why you should start using Java 8 — Part 1
Java 9 will be releasing on 27 July ,but there are lot of developers out there who are still writing code in java 7 style despite of having java 8 as compiler.
Java is one of the language which has picked functional programming paradigm. Java 8 provides fluent way to write functional code. Now it makes sense to adopt functional programming over old imperative style and java 8 is helping every possible way to do so.
In this post I would like to explain new features with examples which would let you to think to code in java 8 style and eventually can make your life easy.
Java 8 has following new features
- Lambda expression
- Stream API
- Default methods in interfaces
- Optional class
- Functional Interfaces
- Date Time Api ..
and many more
But for sake of simplicity I would like illustrate Lambda expression and stream api in this post, as we would be using this regularly.
Lambda expression help us to reduce boilerplate code.
This is how we create new runnable in java 7
But using lambda expression provided in java 8 reduces all unnecessary ceremony in the code, below is shorter version of runnable in java 8.
Using java 8 we can write simple and maintainable code, It reduces
return statement and if method body has only one line like we have in above gist, we can avoid writing parenthesis.
Stream API operates on list, they provides better way iterate through list then perform various operations on each item.
Basically we write chain of different functions to list stream then collect result to List, Set ,HashMap, String . Even we can write own custom collector.
Lets understand available operations with the help of example (Read code comments) .
Multiple operations on list
I hope you enjoyed so far, As you would have noticed we didn't write single loop or any global variables except from list variable
We Don’t write for loop any more in java 8
By using stream API we can make code more readable and maintainable.
Now lets take one real world example
List sub directories of given folder and get list in string separated by comma(,)
Lets say If root folder is A and B, C, D, E, F are folders resides in A. We want to print “B,C,D,E,F”.
Imagine if you wanted to do it in old way of java 7, How would you do it ? We would need to iterate through list then create StringBuilder variable in which we would add folder name while iterating then appending comma(,) but wait it will append comma(,) in the end of string, again we need to trim last comma(,)
So how you would feel after writing that code, Would you be proud after writing that code.
Let’s see how we can do it in Java 8.
thats all only three lines of would do the magic. You can go through java documentation for stream api.
Next post I will go through
flatmap and other cool stuff we can do with stream api in java. Please leave comment or any suggestion if any.