Thursday, August 20, 2015

Loop iteration redefined with java 8 Stream


for loop is there in many programming languages like C, C++ java C# etc and it is used mainly iterating contents of same type.

for loop has come a long way in Java 8 with new forEach() method in java.util.stream.Stream class.

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
List  countries = Arrays.asList("India", "Australia", "England", "South Africa");

for(int i=0; i < countries.size(); i++)
{
  System.out.println(countries.get(i));
}
So when foreach loop or advanced for loop was added on Java 5, we started to following style of looping over Collection or List :
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));

Wednesday, August 19, 2015

Time and Date APIs in Java 8

The standard date and time classes prior to Java SE 8 are poor. By tackling this problem head-on, Joda-Time has become the de facto standard date and time library for Java.

For example, the existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe, leading to potential concurrency issues for users—not something the average developer would expect to deal with when writing date-handling code.

Some of the date and time classes also exhibit quite poor API design. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive.

These issues, and several others, have led to the popularity of third-party date and time libraries, such as Joda-Time

The new changes will appear in the Java SE8 package java.time.

A selection of key features:
  • LocalDate - date without time
  • LocalTime - time without date
  • Instant - an instantaneous point on the time-line
  • DateTime - full date and time with time-zone
  • DateTimeZone - a better time-zone
  • Duration and Period - amounts of time
  • Interval - the time between two instants
  • A comprehensive and flexible formatter-parser

Tuesday, August 18, 2015

Stream Collection types

Java is inheritably sequential and there is no direct mean to introduce parallel processing at library level, Stream API is going to fill that gap. By using this, you can filter elements of collection on given criterion e.g. if you have a List of employees, you can filter all employees based upon their name, department and so on.

Stream API allows you to process Collection both sequentially and parallel. This is also useful for bulk data operation. You can create a sequential and parallel stream as follows :

List employees = getListOfEmployees();
 
// sequential version
Stream  stream = employees.stream();
 
//parallel version
Stream  parallelStream = employees.parallelStream();

Collection and Stream

Collection interface is enhanced to provide stream support. It now has a stream() method which returns a sequential Stream with this collection as its source. Once you get the reference of stream, you can perform bulk data operations with this collection.

One of the important things to note is that Stream do not modify the original source. For every operation, a new Stream is created and original collection remains unmodified. Similarly, you cannot reuse Stream either. Reusing a closed stream will throw IllegalStateException as shown below:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
    at java.util.stream.AbstractPipeline.(AbstractPipeline.java:203)
    at java.util.stream.ReferencePipeline.(ReferencePipeline.java:94)
    at java.util.stream.ReferencePipeline$StatelessOp.(ReferencePipeline.java:618)
    at java.util.stream.ReferencePipeline$2.(ReferencePipeline.java:163)
    at java.util.stream.ReferencePipeline.filter(ReferencePipeline.java:162)
    at Test.main(Test.java:33)

It supports functional programming idioms such as map and reduce along with parallel processing capability, support for filtering elements from Collection.


Stream operations 

Stream operations are mainly divided into two categories : intermediate and terminal operations. Intermediate operations such as filter() or map() returns a new Stream, while terminal operations such as Stream.forEach() produce a result or side effect. After the terminal operation, the stream pipeline is considered consumed, and can no longer be used.

Intermediate operations are also of two types stateless and stateful. As name suggests, stateless operations doesn't retain any state from previously processed element. For example : filter() and map(). On the other hand distinct() and sorted() are example of stateful operations, which can have state from previously processed elements, while processing new elements.

Important methods in java.util.stream

Return Type
Method Name
Short Description
Long
count()
Returns the count of elements in this stream
Stream
Distinct()
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
static Stream
Empty()
Returns an empty sequential Stream.
Stream
Filter(Predicate predicate)
Returns a stream consisting of the elements of this stream that match the given predicate.
Stream
flatMap(Function> mapper)
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
void
forEach(Consumer action)
Performs an action for each element of this stream.
static Stream
generate(Supplier s)
Returns an infinite sequential unordered stream where each element is generated by the provided Supplier.
static Stream
iterate(T seed, UnaryOperator f)
Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc.
Stream
Limit(long maxSize)
Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.
Stream
map(Function mapper)
Returns a stream consisting of the results of applying the given function to the elements of this stream.
Optional  
max(Comparator comparator)
Returns the maximum element of this stream according to the provided Comparator.
Optional  
min(Comparator comparator)
Returns the minimum element of this stream according to the provided Comparator.
Stream
skip(long n)
Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream.
Stream
sorted()
Returns a stream consisting of the elements of this stream, sorted according to natural order.
Stream
Sorted (Comparator comparator)
Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.
Object[]
toArray()
Returns an array containing the elements of this stream.

Tuesday, August 11, 2015

Default Methods

Default Methods in Java 8

In my previous articles, we have looked at LambdaExpressions and Method References. In this latest article in the series, we will be looking at Default methods.


What is Default method?

Default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface.

We specify that a method definition in an interface is a default method with the default keyword at the beginning of the method signature. All method declarations in an interface, including default methods, are implicitly public, so you can omit the public modifier.

Extending Interfaces that contains default methods

When you extend an interface that contains a default method, you can do following:
  • Not mention the default method at all, which lets your extended interface inherit the default method.
  • Re declares the default method, which makes it abstract.
  • Redefine the default method, which overrides it.

Lamda Expression in Java 8


Lambda Expressions

Why Lambda in Java

Since beginning, the Java language always remained Object first language. Everthing should come after an Object After working with functional language like JavaScript, it becomes clear to one how Java enforce its strict object-oriented nature and strict typed on the source code.
You see Functions are not important for Java. On their own they cannot live in Java world.

Functions are first class citizens in a functional programming language. They exists on their own. You can assign them to a variable and pass them as arguments to other functions.
JavaScript is one of the best example of an FP language

Lambda expression adds that missing link of functional programming to Java. Lambda expression let us have functions as first class citizen. Although this is not 100% correct, we will shortly see how!

In Java, the lambda expressions are represented as objects, and so they must be bound to a particular object type known as a functional interface. We will see in detail about Functional interface here.

Lambda expressions can only appear in places where they will be assigned to a variable whose type is a functional interface.

Introduction to Lambda Expressions

As mentioned in the java docs 
One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data. 

What is a Lambda Expression ?

Lambda expressions are anonymous methods, aimed at mainly addressing the Anonymous classes's syntax by replacing the machinery of anonymous inner classes with a lighter-weight mechanism in applicable cases.

Lambda Expressions enable you to encapsulate a single unit behaviour and pass it to other code.

Lambda expressions are supported by the following features:

Method References:
Method references are compact, easy-to-read lambda expressions for methods that already have a name.

Default Methods:
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older version of those interfaces. They are interface methods that have an implementation and default keyword at the beginning of method signature.

New and Enhanced APIs

In Java SE8, new classes have been introduced and existing classes have been enhanced to take advantage of lambda expressions and streams. We can find most of the new and enhances classes in following packages:

Java.util: An existing package in which we integrated Java Collection Framework with streams and provide general utility functionality used by streams.
 • Java.util.function: A new package that contains general purpose functional interfaces that provide target types for lambda expressions and method references.
 • Java.util.stream: A new package that contains the majority of interfaces and classes that provide functionality to streams and aggregate operations.

Modified Packages: All the Wrapper classes have been enhanced with methods that are suitable for target of method references. For example: Integer.sum





Method References

Method References in Java 8 


In my previous articles, we have looked at LambdaExpressions and Default methods. In this latest article in the series, we will be looking at Method References.

What  is Method References?
This feature is introduced in Java 8 for Lambda Expression. So it is but obvious that this is going to be used best with Lambda expressions.
Lambdas let us define anonymous methods and treat them as instances of functional interfaces.

Method references let us accomplish the same thing, but with existing methods. Method references are similar to lambdas in that they require a target type. However, instead of providing method implementations, they refer to the methods of existing classes or objects.
public class Employee {

    String name;
    LocalDate birthday;
    String emailAddress;

    public int getAge() {
        // ...
    }
   
    public Calendar getBirthday() {
        return birthday;
    }   

    public static int compareByAge(Person a, Person b) {
        return a.birthday.compareTo(b.birthday);
    }}

Let’s assume that we have an array of Employees as:
List  employeeList;
 
Employee [] employeeArray = employeeList.toArray(new Employee[employeeList.size()]);
Now if we need to sort them by their age we need to write a new comparator class as follows:
class EmployeeAgeComparator  implements Comparator 
{
  public int compare(Employee a, Employee b) {
  return a.getBirthday().compareTo(b.getBirthday());
}
}
Now we can call the sorting logic in following ways: 
//Without method reference
Arrays.sort(employeeArray, new EmployeeAgeComparator());
         
//With lambda expression
Arrays.sort(employeeArray,
            (Employee a, Employee b) -> {
                return a.getBirthday().compareTo(b.getBirthday());
            }
        );
         
//With method reference
Arrays.sort(employeeArray, Employee::compareByAge);

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...