Posts

Showing posts with the label lambda expression

Lambda Expression v/s Anonymous Inner Class - Java 8

Image
Lambda Expression is new feature of Java 8. Before Java 8 Anonymous Inner Class was very useful to provide method local implementation of any interface like ActionListner or EventListener etc. With Java 8 if the interface is a Functional Interface we can use Lambda Expression to provide implementation. Both of these can implement an Interface but there are subtle differences between them. Following are to the point differences between them - Anonymous Inner class can implement any interface but Lambda can implement only Functional Interface , the interface with only one abstract method. Anonymous Inner Class can have state variables but Lambda Expression cannot. Lambda Expression is stateless. Lambda Expression can only access final or effectively final variables of containing method. Scope - Anonymous Inner Class creates a new scope whereas Lambda Expression does not. Lambda executes always within scope of surrounding context. To explain it better, in Anonymous Inner Clas...

Lambda Expression Basics and Syntax - Java8

Image
In simple term, a Lambda Expression is implementation of a Functional Interface. Lambda Expression is a way to provide implementation of a functional interface without creating a Class or Anonymous Inner Class. Note that Lambda can implement only a functional interface. Read more about Functional Interface Here is a functional interface named Processor which has single abstract method called process And let say there is processValue method, which takes a value and a Processor object as input, apply processor on the value and return the result. private int processValue(int value, Processor processor) { return processor.process(value); } Call processValue method using Anonymous Inner Inner Class as implementation of Processor interface. processValue(10, new Processor() { @Override public int process(int input) { return input * 2; } }); It’s easily noticeable the unnecessary verbose code that we had to write for anonymous inner class. Only important line which is d...