Java 8 - it has been making headlines as the version which brings dramatic changes to Java. And I believe its true. I have been using Java 8 for the last few months and using Java 8 features has really brought changes in the way I write code and sometimes even the way I think about code!

Most of the changes is in the way we deal with Collections. And most of our daily life as a programmer revolves around manipulating or using Java Collections. Java 8 has brought in functional programming and Lambda expressions. There are many examples out there in the WWW which go to the intricacies of Lambda expressions and Java 8 features. Here I’ll jot down some notes which I found to be useful. Its no way an introduction or tutorial, its just some notes I have made which’ll help in understanding Java 8 features.

Functional Interfaces

Any interface with just one non-default method. -Even though not necessary, we can enforce this constraint by annotating an interface with @FunctionalInterface

Default Methods

An interface method with modifier ‘default’. Should have method implementation.

Lambdas

Short-cut way to implement anonymous inner classes for functional interfaces. Syntax: parameter || (parameters) || () -> expression || statement || { statements }
  • Can reference external variables which are effectively final in the lambda body
  • ‘parameters’ - parameters for the functional interface method. Datatype is not required. Eg: (String s1, int i), (s1, i)
  • a single ‘expression’ can be used if the lambda body is just a return statement

Method Reference

Syntax: ClassName::methodName To refer constructors: ClassName::new
  • Can be used anywhere where a lambda or functional interface implementation is expected.
  • The referred method should be having same signature as of the functional interface method
 

Functions like foreach(), stream(), filter(), map(), findFirst() along with Consumer, Function and Predicate make life a hell lot of easy in dealing with Java Collections. Java 8 also brings functional programming to Java world with its lambdas. That means we can now pass a function to a function and return a function from a function! That brings a lot of changes in which we write Java programs. Java 8 also brings a new Date/Time API as well as some utils like Base64 encoding in the default library set.

Happy coding :)