This is a follow up on the previous article part 1 for Java 8 by example.
This should be helpful for those who already know java and would like to quickly go over what’s Java 8 all about in short with some examples!
Lambdas in general
Lambda expressions can only be used where they will be assigned to a variable whose type is a functional interface. The Arrow Token “->” is called the lambda operator.
A functional interface is simply an interface with a single abstract method. Example:
Now lambda allows us to define the method above “process” without the need to state the obvious, such as the class declaration and argument type.
The code would look like below where msg is the variable of type String which is inferred:
SingleAbstractMethod sam = (msg) -> System.out.println(msg);
And we would invoke the method like this:
sam.process("testing new message on a SAM");`
The pre java 8 way to create a instance from a anonymous inner class here Runnable would be like below:
The java 8 lambda way would look like below where empty parenthesis is used for no-args method:
Next up, using lambdas
Here’s a traditional way to sort a collection.
Now if you had to sort the collection in a case insensitive way then this can be done as below:
Now to do it the java 8 way which would be a lot more effecient.