September 28, 2016

Parallel Streams

The Streams API that came with Java 8 enabled functional programming by taking advantage of the new lambda functionality and the method references. One of the most popular features of streams is that they support lazy evaluation. Another very popular feature of streams is that they are capable of processing results concurrently using multiple threads. In this article, we will examine the main points to consider when using a parallel stream.

Creating a parallel stream is really simple; you just have to designate that your stream is parallel and the operations are done in parallel automatically for you. There is no need to write any threading code to make it happen. There are 2 ways to create a parallel stream: you can either create it from an existing stream, by calling the parallel() method, or use an extension method that has been added to the Collection interface, as below:
 Stream<String> stream = Stream.of("cat", "dog");  
 Stream<String> parallelStream = stream.parallel();  
 Stream<String> parallelStream2 = Arrays.asList("cat", "dog").parallelStream();  

September 27, 2016

Optionals in Java 8 and How to Use Them

Since the release of Java 8, NullPointerExceptions shouldn't be common anymore. Before Java 8, your code was probably full of "if statements" to check if a variable was null. Still, it was impossible to catch every NullPointerException out there. With Java 8, Oracle attempted to solve this issue. They didn’t invent the holy grail, but they did make our lives as developers much easier by helping prevent code smells and those nasty Exceptions. Now, if you start a new project, you should definitely use Java 8 to avoid NullPointerExceptions.

So what exactly did Oracle do to help us in our misery? They introduced Optionals. [1]

You may have heard of Optionals already a few times, but you maybe dont know exactly know how to use them in the right way. If you use them in the wrong way, it is like you wouldnt use Optionals at all. So let's take a look how Optionals could be used.

Java 8 Date and Time API [Quick Introduction]

Along with new language features like lambda expressions and streams, Java 8 has also introduced a new concept to deal with dates and times. Working with dates and times prior to Java 8 was a little tricky and cumbersome, which led to the popularization of third-party time libraries like Joda-Time. Even for those starting to learn Java with version 8, it is still important to be able to understand the code written the old way. In this article, we will examine the core differences between the old and new way.

First of all, in order to use the new classes, import the java.time package like this:
 import java.time.*;