Java 8 Parallel Streams

Java8
Using Parallel Stream Java 8 streams comes with some convenience to do parallel processing by just calling the method parallel() or parallelStream() and all the magic happens behind the scene. But it comes with a price. If you are not careful about a few things it can actually backfire and cause problems with performance or may even cause concurrency problems or race conditions. A few things to take into consideration: Are the operations in the stream stateful or stateless? Consider the following example: words.stream() .filter( word->word.startsWith("a")||word.startsWith("e")||word.startsWith("i") ) .forEach(System.out::println); Here the filter operation is stateless operation because it only operates on one element at a time. It does not depend on any other elements to complete the operation. Consider the following. Inorder for the elements of the stream to be sorted…
Read More

Java 8 Optionals pattern

Java8
What is an optional? An optional is a concept that was introduced to represent the case when no result is produced. An optional wraps a value that is returned from a function and now your function can return a <no value> wrapped in an optional. This means that the optional can be empty. For example consider the following stream which finds the user with max age with name "Jacob". What if the list of users is empty. In that case we have nothing to return . This is where optionals come handy. It gives a way to specify that the function can return a no value. List<User> users = new ArrayList<>(); Optional<User> jacob = users .stream() .filter(user -> user.getName().equals("Jacob")) .reduce( MaxAgeHelper::maxAgeUser); public class MaxAgeHelper { public static User maxAgeUser(User user1,…
Read More